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.
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 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 have been working on building an Rest API for the hell of it and I have been testing it out as I go along by using curl from the command line which is very easy for CRUD
I can successfully make these call from the command line
curl -u username:pass -X GET http://api.mysite.com/pet/1
curl -d '{"dog":"tall"}' -u username:pass -X GET http://api.mysite.com/pet
curl -d '{"dog":"short"}' -u username:pass -X POST http://api.mysite.com/pet
curl -d '{"dog":"tall"}' -u username:pass -X PUT http://api.mysite.com/pet/1
The above calls are easy to make from the command line and work fine with my api, but now I want to use PHP to create the curl. As you can see, I pass data as a json string. I have read around and I think I can probably do the POST and include the POST fields, but I have not been able to find out how to pass http body data with GET. Everything I see says you must attached it to the url, but it doesn't look that way on the command line form. Any way, I would love it if someone could write the correct way to do these four operations in PHP here on one page. I would like to see the simplest way to do it with curl and php. I think I need to pass everything through the http body because my php api catching everything with php://input
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET
See #Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
$result['status'] is the HTTP response code
$result['data'] an array with the JSON response parsed
$result['header'] a string with the response headers
Hope it helps
For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.
$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)
<?php
if(!isset($_GET['json']))
die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>
I was Working with Elastic SQL plugin.
Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
I'm trying, without success, to get some results using Bing's Image search API without HTTP/Request2.php component (as used in the official examples).
I understand that the only two required parameters to make a very primitive call are q which is the query string and the subscription key. The key must be sent using headers. After looking around I found this very simple example to send headers with PHP:
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$aHTTP = array(
'Ocp-Apim-Subscription-Key' => 'xxxxxxx',
);
$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);
echo $contents;
But it does not output anything. Would you kindly help me with a very basic example of use of Bing's API?
SOLVED
Thanks to Vadim's hint I changed the way headers are sent and now output is a Json encoded result. (Remember to add your API subscription key.)
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: xxxxx'
));
$content = curl_exec($ch);
echo $content;
Just another tip. The syntax of query filters and other parameters change form version to version. For example the following work correctly in version 5.0:
To search only for JPEG images of cats and get 30 results use:
q=cats&encodingFormat='jpeg'&count=30
To search only for 'portrait' aspect images with size between 200x200 and 500x500 use:
q=cats&aspect=Tall&size=Medium
Try using cURL
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$key = "xxxxxxx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key');
$content = curl_exec($ch);
echo $content;
Here is my working code..
Replace ******** with your bing subscription key.
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=microsoft-surface&count=6&mkt=en-US";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: *******************'
));
$contents = curl_exec($ch);
$myContents = json_decode($contents);
if(count($myContents->value) > 0) {
foreach ($myContents->value as $imageContent) {
echo '<pre/>';
print_r($imageContent);
}
}
I saw this post on consuming a web service using CURL: Consume WebService with php
and I was trying to follow it, but haven't had luck. I uploaded a photo of the web service I'm trying to access. How would I formulate my request given the example below, assuming the URL was:
https://site.com/Spark/SparkService.asmx?op=InsertConsumer
I attempted this, but it just returns a blank page:
$url = 'https://xxx.com/Spark/SparkService.asmx?op=InsertConsumer?NameFirst=Joe&NameLast=Schmoe&PostalCode=55555&EmailAddress=joe#schmoe.com&SurveyQuestionId=76&SurveyQuestionResponseId=1139';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$xmlobj = simplexml_load_string($result);
print_r($xmlobj);
Really, you should probably look at the SOAP extension. If it is not available or for some reason you must use cURL, here is a basic framework:
<?php
// The URL to POST to
$url = "http://www.mysoapservice.com/";
// The value for the SOAPAction: header
$action = "My.Soap.Action";
// Get the SOAP data into a string, I am using HEREDOC syntax
// but how you do this is irrelevant, the point is just get the
// body of the request into a string
$mySOAP = <<<EOD
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope>
<!-- SOAP goes here, irrelevant so wont bother writing it out -->
</soap:Envelope>
EOD;
// The HTTP headers for the request (based on image above)
$headers = array(
'Content-Type: text/xml; charset=utf-8',
'Content-Length: '.strlen($mySOAP),
'SOAPAction: '.$action
);
// Build the cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $mySOAP);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Send the request and check the response
if (($result = curl_exec($ch)) === FALSE) {
die('cURL error: '.curl_error($ch)."<br />\n");
} else {
echo "Success!<br />\n";
}
curl_close($ch);
// Handle the response from a successful request
$xmlobj = simplexml_load_string($result);
var_dump($xmlobj);
?>
The service requires you to do a POST, and you're doing a GET (curl's default for HTTP urls) instead. Add this:
curl_setopt($ch, CURLOPT_POST);
and add some error handling:
$result = curl_exec($ch);
if ($result === false) {
die(curl_error($ch));
}
This is the best answer because using this once you need to login then
get some data from webservices(third party site data).
$tmp_fname = tempnam("/tmp", "COOKIE"); //create temporary cookie file
$post = array(
'username=abc#gmail.com',
'password=123456'
);
$post = implode('&', $post);
//login with username and password
$curl_handle = curl_init ("http://www.example.com/login");
//create cookie session
curl_setopt ($curl_handle, CURLOPT_COOKIEJAR, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $post);
$output = curl_exec ($curl_handle);
//Get events data after login
$curl_handle = curl_init ("http://www.example.com/events");
curl_setopt ($curl_handle, CURLOPT_COOKIEFILE, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($curl_handle);
//Convert json format to array
$data = json_decode($output);
echo "Output : <br> <pre>";
print_r($data);
echo "</pre>";