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.
Related
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.
```` echo "<br/><br/>Generating Form Digest<br/>";
// Initialize curl for Getting the Form Digest
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, "https://xxxxxxxxxxxxxx.sharepoint.com/_api/contextinfo");
// Set curl Method
curl_setopt($ch, CURLOPT_POST, true);
// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Length: 0',
'Accept : application/json;odata=verbose',
// 'Authorization: Bearer ' . $access_token,
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $url_client);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo "<br/> Result of API Context :<br/>";
print_r(json_decode($result));
curl_close($ch);
echo "<br/><br/><br/>Uploading File<br/>";
// API URL with the file attached
$api_URL =
"https://xxxxxxxxxxxxxxxxxxxxxxxxxx.sharepoint.com/_api/web/GetFolderByServerRelativeUrl
('Documents')/Files/add(url='uploads/{$_FILES["fileToUpload"]["name"]}',overwrite=true)";
echo $api_URL;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $api_URL );
curl_setopt($ch, CURLOPT_POST, true);
// Set HTTP Header for POST request
// Set the headers in the curl object
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
// 'Content-Type: application/x-www-form-urlencoded',
"Authorization: Bearer {$json_result->access_token}",
"Content-Length: {$filesize}",
"X-HTTP-Method: MERGE",
//"X-RequestDigest:",
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
echo "<br/> RESULT OF Upload file CURL<br/> " ;
// Convert result to JSon
$json_result = json_decode($result);
// Print Json Result
print_r($json_result);
// Close CURL
curl_close($ch);````
What I'm trying to do is to create a PHP webpage that will take a file ans an iput and upload it directly yo a shrepoint library
I'm generating access token before this code is executed
I'm getting the "404 unauthorized" error when form digest is generated, please help !!
I'm trying to use Application Only Authentication, as described here:
https://developer.twitter.com/en/docs/basics/authentication/overview/application-only
I'm using the following PHP code to do so.
if(empty($_COOKIE['twitter_auth'])) {
require '../../social_audit_config/twitter_config.php';
$encoded_key = urlencode($api_key);
$encoded_secret = urlencode($api_secret);
$credentials = $encoded_key.":".$encoded_secret;
$encoded_credentials = base64_encode($credentials);
$request_headers = array(
'Host: api.twitter.com',
'User-Agent: BF Sharing Report',
'Authorization: Basic '.$encoded_credentials,
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
'Content-Length: 29',
'Accept-Encoding: gzip'
);
print_r($request_headers);
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
$attempt_auth = curl_exec($ch);
print_r($attempt_auth);
}
It should return JSON with the token in it, but instead it returns gobbledygook, as seen in the image below:
I'm sure I'm missing some very simple step, where am I going wrong?
If I send the curl request without the headers, it returns an error in JSON format as expected, so is there something wrong with my headers?
You have few options here. Instead of setting header directly, use below
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
If you set header directly then you should use
print_r(gzdecode($attempt_auth));
See below thread as well
Decode gzipped web page retrieved via cURL in PHP
php - Get compressed contents using cURL
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);
I want to make a post to a server I have by using php.
I was thinking in curl but all examples I find, urlfy data and I have to send a json file but not in the url.
I already have the json in an array : 'key'=>'value'...
I have to add headers, I think I can with this:
curl_setopt($ch,CURLOPT_HTTPHEADER,array('HeaderName: HeaderValue','HeaderName2: HeaderValue2'));
but I don't knoe how to add my array and post it.
Any idea?
I need to add a json like this:
[{"a":"q",
"b":"w",
"c":[{
"e":"w",
"r":"t"
}]
}]
Here how you can post the data using CURL, and as you mentioned you already have a json you can do so as
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'your api end point');
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); // $postfields is the json that you have
$request_headers = array();
$request_headers[] = 'HeaderName: HeaderValue','HeaderName2: HeaderValue2';
$request_headers[] = 'Content-Type: application/json','Content-Length: ' . strlen($postfields) ;
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
$response = curl_exec($ch);
curl_close ($ch);