Get REST response from parse.com for search functionality - PHP - php

I'm creating a search functionality for my website and I'm using Parse.com for storing data. I have a class Posts with a "plainContent" column which stores the content of my article in plain text format. I've found this article:
http://blog.parse.com/learn/engineering/implementing-scalable-search-on-a-nosql-backend/
which is very useful. I've added the cloud code which splits my plain text into single words and puts them into an array. Now I have my Posts with an extra column "words" which stores an array with all the single words for article's content. I got the the step of retrieving data now but the problem is the following code:
curl -v -X GET
-H "X-Parse-Application-Id: ${APPLICATION_ID}"
-H "X-Parse-REST-API-Key: ${REST_API_KEY}"
-G
--data-urlencode 'where={"hashtags":{"$all":["#parse", "#ftw"]}}'
"https://api.parse.com/1/classes/Post"
precisely the --data-urlencode row which in my case would be:
--data-urlencode 'where={"words":{"$all":["word1", "word2"]}}'
I can't create the curl query with PHP. What exactly is the $all variable in the example?
Here's my php script:
$url = 'https://api.parse.com/1/classes/Posts?';
$headers = array(
"Content-Type: application/json",
"X-Parse-Application-Id: " . $MyApplicationId,
"X-Parse-REST-API-Key: " . $MyParseRestAPIKey
);
$query = urlencode('where={"words":{"$all":["parseobjectcontains", "compatible"]}}');
$ch = curl_init($url.$query);
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($handle);
curl_close($handle);
$array = json_decode($data);
var_dump($array);
This script returns all results without filtering.
The question is how to build this sentence to reflect the example in the article from the link? What should be that $all variable?
$query = urlencode('where={"words":{"$all":["parseobjectcontains", "compatible"]}}');
EDIT
I had an error in my script:
$ch = curl_init($url.$query);
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
Correction:
$handle = curl_init($url.$query);
//$handle = curl_init();
//curl_setopt($handle, CURLOPT_URL, $url);

Assuming $all is needed as it is you have shown in your code (as per parse.com). Here are few catch.
1) You are doing urlencode over the whole request parameter. But actually you have to do it over the value of where in your example. So change it as below:
$query = 'where='.urlencode('{"words":{"$all":["parseobjectcontains", "compatible"]}}');
2) The data you are posting here is not json, it is actually key=value pared data. So remove Content-Type: application/json thing from your code.
That's all!

Related

Choosing the data type to post in a curl payload

I have an application that i want to access via curl and the way i am doing that is via a curl api. I am inserting a document with the details i have. The document accepts a string, geopoint and integer32/64.
Since the server is some sort of database, is it possible to decide what data type to send as a json payload since some of the fields must be strings and others integers
<?php
$YOUR_API_KEY = base64_encode("77777");
$ch = curl_init();
$payload = '{"property_owner_id":"'.$property_owner_id.'","property_name":"'.$property_name.'","property_country":"'.$property_country.'","property_address":"'.$property_address.'","property_city":"'.$property_city.'","property_star_rating":'$property_star_rating',"property_reviews_score":'$property_reviews_score',"property_price_per_night_usd":'$property_price_per_night_usd',"property_price_per_night_euro":'$property_price_per_night_euro',"property_price_per_night_pound":'$property_price_per_night_pound',"property_price_per_night_sfr":'$property_price_per_night_sfr',"property_price_per_night_auz":'$property_price_per_night_auz',"property_price_per_night_rem":'$property_price_per_night_rem',"property_price_per_night_yen":'$property_price_per_night_yen',"property_image":"'.$property_image.'","property_tv":"'.$property_tv.'","property_radio":"'.$property_radio.'","property_breakfast":"'.$property_breakfast.'","property_bed_type":"'.$property_bed_type.'","property_kitchennete":"'.$property_kitchennete.'","property_region":"'.$property_region.'","property_chain_name":"'.$property_chain_name.'","property_status":"'.$property_status.'","property_maximum_occupancy_capacity":'$property_maximum_occupancy_capacity',"property_remaining_occupancy_capacity":'$property_remaining_occupancy_capacity',"property_date_added":"'.$property_date_added.'","property_date_updated":"'.$property_date_updated.'","property_coordinates": ['$coordinates']}';
$pe = json_encode($payload);
curl_setopt($ch, CURLOPT_URL, 'http://localhost:8108/collections/mh_props/documents');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $pe);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $YOUR_API_KEY . ':' . '');
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
For instance
"property_city":"'.$property_city.'","property_star_rating":'$property_star_rating',
$property_city should be a string and $property_star_rating should be an integer. I have prepared some data that is stored in $property_city as a string and $property_star_rating as an integer.
This is the curl equivalent without php
curl "http://localhost:8108/collections/mh_props/documents" -X POST \
-H "Content-Type: application/json" \
-H "X-TYPESENSE-API-KEY: " \
-d '{"property_owner_id":"1","property_name":"Louvre Museuem","property_country":"", "property_address":"","property_city":"","property_star_rating":4,"property_reviews_score":6,"property_price_per_night_usd":100,"property_price_per_night_euro":120,"property_price_per_night_pound":130,"property_price_per_night_sfr":200,"property_price_per_night_auz":122,"property_price_per_night_rem":134,"property_price_per_night_yen":211,"property_image":"","property_tv":"","property_radio":"","property_breakfast":"","property_bed_type":"","property_kitchennete":"","property_region":"","property_chain_name":"","property_status":"","property_maximum_occupancy_capacity":23,"property_remaining_occupancy_capacity":20,"property_date_added":"","property_date_updated":"","property_coordinates": [48.86093481609114, 2.33698396872901]}'
Is it possible to make a data type distinction when posting the data using json?
Build up some array first containing your data.
For example
$a = ["key1" => 3, "key2" => "344"];
and do some json_encode($a) which will automatically do the number/string conversion part for you
Result will be
{"key1":3,"key2":"344"}
This will guarantee to have always a proper json string without fiddling around with string concats
PS: JSON does not care about complex types like geopoints etc. Therefore you might always want to convert to simple types like numbers and/or strings

Modifying php script to have POST request in cURL for a JSON upload

I have an existing PHP script, which essentially connects to 2 databases each on a different server and performs a few MySQL queries on each. The ultimate results are stored in a data array which is used to write said results into a JSON file.
All of this works perfectly. The data is inserted into the mysql table correctly and the JSON file is exactly the way it should be.
However, I need to add a block to the end of my script that makes a POST request to one of our affiliate's API and upload the info there. We're currently manually uploading this JSON file to the api instance but we have the configuration data for their server to use in a POST request now so that when this script is run it automatically sends the data rather than us having to manually update it.
The main thing is I'm not exactly sure how to go about that. I've started with code for doing this but I'm not familiar with cURL so I don't know the best way to structure this in php.
Here is an example the affiliate gave me in cURL command line syntax:
curl \
-H "Authorization: Token AUTH_TOKEN" \
-H "Content-Type: CONTENT_TYPE" \
-X POST \
-d '[{"email": "jason#yourcompany.com", "date": "8/16/2016", "calls": "3"}]'
\
https://endpoint/api/v1/data/DATA_TYPE/
I have my auth token, my endpoint URL and my content type is JSON, which can be seen in my code below. Also, I have an array instead of the example for the body above.
and here's the affected part of my code:
//new array specifically for the final JSON file
$content2 = [];
//creating array for new fetch since it now has the updated extension IDs
while ($d2 = mysqli_fetch_array($data2, MYSQLI_ASSOC)) {
// Store the current row
$content2[] = $d2;
}
// Store it all into our final JSON file
file_put_contents('ambitionLog.json', json_encode($content2, JSON_PRETTY_PRINT ));
//Beginning code to upload to Ambition API via POST
$url = 'endpoint here';
//Initiate CURL
$ch = curl_init($url);
//JSON data
$jsonDataEncodeUpload = json_encode($content2, JSON_PRETTY_PRINT);
//POST via CURL
curl_setopt($ch, CURLOPT_POST, 1);
//attach JSON to post fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncodeUpload);
//set content type
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//execuate request
$postResult = curl_exec($ch);
So, like I said, nothing about the file or the data needs to be changed, I just need to have this cURL section take the existing array that's being written to a JSON file and upload it to the API via post. I just need help making my php syntax for curl match the command line example.
Thanks for any possible help.
Have you tried with file_get_contents ( http://en.php.net/file_get_contents ).
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
I have found the answer on stackoverflow How to post data in PHP using file_get_contents?
Here is worked example of code. Check $err may be it will be helpful.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST('data'));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);

Slack Slash Command - Getting user icon URL with username (PHP)

I am new at programming Slash commands in Slack. For one of my commands, I have a username and need to retrieve the user icon URL. I am using PHP to code them.
I was planning on using users.profile.get, since the tutorial here shows that one of the fields returned is the user icon URL.
However, I am trying to find examples on how to make a call to this method and have not found any. Could anybody give me a quick example of the call, including how to send the parameters?
This is how far I got:
$slack_profile_url = "https://slack.com/api/users.profile.get";
$fields = urlencode($data);
$slack_call = curl_init($slack_profile_url);
curl_setopt($slack_call, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($slack_call, CURLOPT_POSTFIELDS, $fields);
curl_setopt($slack_call, CURLOPT_CRLF, true);
curl_setopt($slack_call, CURLOPT_RETURNTRANSFER, true);
curl_setopt($slack_call, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: " . strlen($fields))
);
$profile = curl_exec($slack_call);
curl_close($slack_call);
I basically have $token and $user_name and need to get the profile picture URL. How do I format $token and $username as $data? Is the call correct?
If anybody recommends doing this a different way, I would appreciate any advice as well.
Thank you so much!
To get data into the right format to post to Slack is pretty straight forward. There's two options (POST body or application/x-www-form-urlencoded).
The query string for application/x-www-form-urlencoded is formatted like a get URL string.
https://slack.com/api/users.profile.get?token={token}&user={user}
// Optionally you can add pretty=1 to make it more readable
https://slack.com/api/users.profile.get?token={token}&user={user}&pretty=1
Just request that URL and you will retrieve the data.
The POST body format will use a similar code to what you have above.
$loc = "https://slack.com/api/users.profile.get";
$POST['token'] = "{token}";
$POST['user'] = "{user}";
$ch = curl_init($loc);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $POST);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if ($error = curl_errno($ch)) { echo $error; }
//close connection
curl_close($ch);
echo $result;

Curl works on command line but not in PHP.

I'm trying to upload a .csv file to an API. The API documentation says to post it like this:
curl --user username:password
--request POST
--data-binary #yourfile.csv
https://api.example.com/api
This works perfectly.
in PHP I have it like this:
$data = array('myfile' => 'myfile.csv');
$curl = curl_init('https://api.example.com/api');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_USERPWD, "username" . ":" . "password");
$result = curl_exec($curl);
echo $result;
The results do equal what the API documentation says is the correct response (and is the same response as when using the command line) however it does not actually upload the contents of the file.
is my PHP structure correct? Thanks.

PHP curl is changing JSON before posting it

I have an API written in django, which is able to process the following request correctly.
curl -H "Content-Type: application/json" -d '{"name":"a","description":"b","props": {"Notes":"c"}}' http://127.0.0.1:8000/en/api/asset/ -H 'Authorization: Token 114ada7e487b2cdbc9277d377e4d20640a606bb2'
If I print request.DATA at the Django side I get the following:
(Pdb) print request.DATA
{u'props': {u'Notes': u'c'}, u'name': u'a', u'description': u'b'}
I have the following piece of PHP code which I want to use to make the exact same request
$data_string = json_encode($values['json_parameters']);
error_log($data_string, 0);
//curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
error_log("Method: ".$method, 0);
if ($method == 'POST') {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
}
$data_string contains {"name":"a","description":"b","props":{"Notes":"c"}}.
When this query hits the backend I get the following:
(Pdb) print request.DATA
<QueryDict: {u'{"name":"a","description":"b","props":{"Notes":"c"}}': [u'']}>
What is PHP doing to my JSON before it sends it? How can I post the exact same data using PHP as per my curl request above?
It does work for requests that don't have nested JSON
I'm no PHP expert, but it may not matter: if request.DATA is a QueryDict, you can simply use arealdict = request.DATA.dict() to get a real dict out of it. Should there be any repeated fields this will pick just one of their multiple values, but that shouldn't matter for your specific use case since it seems to have no repeated fields anyway.
Turns out that I was overwriting the application/json header later on in my login code. That is why some requests appeared to work fine.
Sinc eteh content type was not set, Django treated the request as a form post which resulted in the mangled request.DATA.

Categories