I just got API access for one of the website on the internet, and as a new api developer i got into troubles understanding how should i start and with what, So hope you guys guide me . They don't have Documents or tutorials Yet.
If anyone can give me a small example on how to send Http post request that includes Header and body? As what they are mentioning in the API page:
All requests must include an Authorization header with siteid and
apikey (with a colon in between) and it must match with the siteid and
apikey in the request body
In the body the Parameter content type will be application/json. They have also provided a Base URL.
The response will be as application/json.
What should i do? is the request can be sent using AJAX? or there is PHP code for this? i have been reading a lot about this subject but none enter my head. Really hope you guys help me out .
Please let me know if you need more information so i can provide it to you.
EDIT : Problem solved and just posting the small editing that i did to the code that was provided in the correct answer that i marked .
Thanks to Mr. Anonymous for the big help that he gave me . His answer was so so close, all what i had to do is just edit his code a little bit and everything went good .
I will list the finial code down bellow in case any other developer had this issue or wanted to do an HTTP request .
First what i did is that i stored the data that i wanted to send over the HTTP in a file with a JSON type :
{
"criteria": {
"landmarkId": 181,
"checkInDate": "2018-02-25",
"checkOutDate": "2018-02-30"
}
}
Second thing as what guys can see what Mr. Anonymous posted .
<?php
header('Access-Control-Allow-Origin: *');
$SiteID= 'My Site Id';
$ApiId= 'My Api Id';
$url = 'Base URL';
// Here i will get the data that i created in Json data type
$data = file_get_contents("data.json");
// I guess this step in not required cause the data are already in JSON but i had to do it for myself
$arrayData = json_decode($data, true);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$SiteID:$ApiID");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Connection: Keep-Alive',
'Authorization: $SiteID:$ApiId'
));
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($arrayData));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
?>
Try this
$site_id = 'your_site_id';
$api_key = 'your_api_key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api-connect-url');
curl_setopt($ch, CURLOPT_POST, 1);
############ Only one of the statement as per condition ###########
//if they have asked for post
curl_setopt($ch, CURLOPT_POSTFIELDS, "$site_id=$api_key" );
//or if they have asked for raw post
curl_setopt($ch, CURLOPT_POSTFIELDS, "$site_id:$api_key" );
####################################################################
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["$site_id:$api_key"] );
$api_response = curl_exec ($ch);
curl_close ($ch);
As asker need to send JSON Payload to API
$site_id = 'your_site_id';
$api_key = 'your_api_key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api-connect-url');
curl_setopt($ch, CURLOPT_POST, 1);
//send json payload
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
"criteria":{
"cityId":9395,
"area":{
"id":0,
"cityId":0
},
"landmarkId":0,
"checkInDate":"2017-09-02",
"checkOutDate":"2017-09-03",
"additional":{
"language":"en-us",
"sortBy":"PriceAsc",
"maxResult":10,
"discountOnly":false,
"minimumStarRating":0,
"minimumReviewScore":0,
"dailyRate":{
"minimum":1,
"maximum":10000
},
"occupancy":{
"numberOfAdult":2,
"numberOfChildren":1
},
"currency":"USD"
}
}
}"
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["$site_id:$api_key", 'Content-Type:application/json'] );
$api_response = curl_exec ($ch);
curl_close ($ch);
Related
Im trying to create a simple api that will post json to an endpoint using curl and php. its giving me an error whereby its saying unsupported media type and i need help seeing what it is i might be doing wrong, here is the code
<?php
$data = array("saleAmount"=>"2000","cashBack"=>"800","posUser"=>"John","tenderType"=>"SWIPE","currency"=>"RTGS","transactionId"=>'0001');
$payload = json_encode($data);
echo $payload;
// prepare curl
$ch = curl_init('http://localhost:9111/api/requests');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/jsonp',
'Content-Length: ' . strlen($payload))
);
// Submit the POST request
$result = curl_exec($ch);
echo json_encode($result);
// Close cURL session handle
curl_close($ch);
?>
The issue is that your API is expecting a different media type than the one you are providing in your quest.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415
Make sure that your API supports the content-type application/json
$url="";//path of api
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')
);
$data = array("saleAmount"=>"2000","cashBack"=>"800","posUser"=>"John","tenderType"=>"SWIPE","currency"=>"RTGS","transactionId"=>'0001');
$data=json_encode($data);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$response=curl_exec($ch);
print_r($response);die;
curl_close($ch);
Append your url in $url and check this once.
I have the same problem as here How to get results from Udemy Api with search? which unfortunately doesn't have an answer.
I'm able to retrieved the title etc, from this URL for example, https://www.udemy.com/api-2.0/courses/238934/?fields[course]=#all (you'll see the results in your browser) this URL works as well https://www.udemy.com/api-2.0/search-suggestions?q=java but not this one https://www.udemy.com/api-2.0/courses/?search=java
As mentioned here https://www.udemy.com/developers/affiliate/methods/get-courses-list/
get /api-2.0/courses/?search=java should work?
Here is my code:
$url = "https://www.udemy.com/api-2.0/courses/?search=java";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$c_id = base64_encode('XXX');
$c_sid = base64_encode('XXX');
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Udemy-Client-Id: '.$c_id.'','X-Udemy-Client-Secret: '.$c_sid.'',"Authorization: base64 encoded value of client-id:client-secret","Accept: application/json, text/plain, */*"));
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$result=curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
$title = $result->title;
If someone could please shed some light on this.
Based on ADyson comments, here is the answer (just update the code with your own clientID and clientSecret ID from Udemy):
I've basically updated the CURLOPT_HTTPHEADER:
Code:
$url = "https://www.udemy.com/api-2.0/courses/?search=java";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
//HTTP username.
$clientID = 'XXX';
//HTTP password.
$clientSecret = 'XXX';
//Create the headers array.
$headers = array(
'Content-Type: application/json',
'Authorization: Basic '. base64_encode("$clientID:$clientSecret")
);
//Set the headers that we want our cURL client to use.
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$result=curl_exec($ch);
// echo curl_getinfo($ch, CURLINFO_HEADER_OUT);
// echo curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
$json = json_decode($result, true);
// return $result;
foreach($json['results'] as $results) {
$title = $results['title'];
echo $title.'<br>';
}
Results: (Course titles based on this search: https://www.udemy.com/api-2.0/courses/?search=java)
Java Programming Masterclass for Software Developers
Java Programming for Complete Beginners
Java In-Depth: Become a Complete Java Engineer!
The Complete Java Certification Course
Etc.
I've been stuck with this problem for a little while now. I am trying to use a REST API to change certain settings of a user like clear a user and set their device to inactive.
The REST calls are made in php which I am pretty new to. Most calls (get and post) are working just fine so I think I understood the basic concept of php and curl but I just can't get put requests working. The problem is that when making the REST call I get a status code 200 in return indicating that everything went fine but when I check the database nothing changed and the device is still active.
I've spent several hours researching this problem here on stackexchange (cURL PUT Request Not Working with PHP, Php Curl return 200 but not posting, PHP CURL PUT function not working) and additionally reading various tutorials.
To me my code looks fine and makes perfect sense because it is similar to many examples I found online. So please help me find my mistake.
$sn = "123456789";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/sn/".$sn);
$data = array("cmd" => "clearUser");
$headers = array(
'Accept: application/json',
'Content-Type: application/json'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$username = 'XXX';
$password = 'XXX';
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$output = curl_exec($ch);
curl_close($ch);
So far as I can see, you have two problems in your code.
Content-Type: application/json is incorrect, I would remove it entirely.
You don't have a Content-Length header.
I suggest trying
$sn = "123456789";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/sn/".$sn);
$data = array("cmd" => "clearUser");
$httpQuery = http_build_query($data);
$headers = array(
'Accept: application/json',
'Content-Length: ' . strlen($httpQuery)
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$username = 'XXX';
$password = 'XXX';
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,$httpQuery);
$output = curl_exec($ch);
curl_close($ch);
You define in the Header 'Content-Type: application/json'. Try to encode your $data to json and then transfer the jsonEncodeteData:
$dataJson = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJson);
perhaps this helps already.
status 200 may not be a success in the case of a PUT request. In a correct semantics (correct implementation of the server) successful PUT returns "201 Created" and, if the client sends empty or somehow wrong content, the server returns "204 No Content".
Lazy programmers may just return "200 Ok" instead of 204 with the meaning "your request is fine, but there is nothing to do with the data".
Try to verify your data and make sure that you send something that is not empty and is conformal to the API specs.
good evening,
I'm already breaking my head for 3 days I'm trying to send a message with the button from a page with a bot made in CURL PHP
I'm trying with CURL and PHP POST GRAPH
without success both of us can help me?
function SendRawResponse($Rawresponse){
$userPageConversation = 't_100005050355547';
$Access_token = "XXXX";
$url = "https://graph.facebook.com/v2.6/".$userPageConversation."/messages?access_token=".$Access_token;
//$url = "https://graph.facebook.com/v2.6/me/messages?access_token=".$Access_token;
$ch = curl_init($url);
$headers = array(
'Content-Type: application/x-www-form-urlencoded',
'charset=utf-8',
);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $Rawresponse);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($Rawresponse));
//curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse));
curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_exec($ch);
$erros = curl_errno($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
var_dump($erros);
var_dump($response);
curl_close($ch);
}
Mensage:
$teste = '{
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Try the postback button!",
"buttons":[
{
"type":"web_url",
"title":"GOOGLE",
"url":"https://www.google.com.br"
}
]
}
}
}}';
SendRawResponse($teste);
erros:
Warning: http_build_query(): Parameter 1 expected to be Array or Object. Incorrect value given
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse)); = Missing message body
According to the docs
you must add domain to the whitelist in FB page settings.
Domains must meet the following requirements to be whitelisted:
Served over HTTPS
Use a fully qualified domain name, such as
https://www.messenger.com/. IP addresses and localhost are not
supported for whitelisting.
I'm trying to make an CURL PUT REQUEST, my code looks like:
public function assignProfile($token, $organizationId, $profileId)
{
//define enviroment and path
$host = enviroment;
$path = "/admin/organizations/".$organizationId."/users";
$data_string = '["'.$profileId.'"]';
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer '.$token.'',
'Content-Length: ' . strlen($data_string)
));
echo "<br>OK<br>";
// execute the request
$output = curl_exec($ch);
// return ID for a new case
$output = json_decode($output);
var_dump($output);
}
Each part looks correct, when I var_dump $path, $host, even $data_string looks correct. However var_dump() at the end throw just NULL
I expect I'm doing something wrong or missing something really important.
May I ask you for some advise?
Thanks
EDIT:
What i do with it:
// define
define("Audavin","here is some uniqe ID");
.
.
.
$Users = new Users;
// this return Auth token ( I verify this work with echo )
$token = $Users->authorization();
// Calling method mentioned above
$Users->assignProfile($token,"here is org id", Audavin);
I would start by making sure the URL you're making the request to actually works and returns a valid response, you can do so by using a simple REST client (like POSTMAN chrome extension for example)
If you do get a response back, try and see if it's indeed a valid JSON, if not, that could be why you're not getting anything back from json_decode (more on return values here: http://php.net/manual/en/function.json-decode.php)
Finally, It is suggested you add curl_close($ch) to the end of your code to make sure your release the curl handle.