Call a REST API in PHP
Solution 2: You can execute second part (Calling API and response): Call API using curl and process based on its response: Please note: Json response from API is depend on API Response, If API is giving response in json format ( can be based on params also ). Solution 1: There are multiple ways to make REST client API call: Use CURL CURL is the simplest and good way to go.
Call a REST API in PHP
Our client had given me a REST API to which I need to make a PHP call. But as a matter of fact, the documentation given with the API is very limited, so I don’t really know how to call the service.
I’ve tried to Google it, but the only thing that came up was an already expired Yahoo! tutorial on how to call the service. Not mentioning the headers or anything in-depth information.
Is there any decent information around how to call a rest api or some documentation about it? Because even in W3schools, they only describe the SOAP method. What are different options for making the rest of API in PHP?
You can access any REST API with PHPs cURL Extension. However, the API Documentation (Methods, Parameters etc.) must be provided by your Client!
// Method: POST, PUT, GET etc // Data: array("param" => "value") ==> index.php?param=value function CallAPI($method, $url, $data = false) < $curl = curl_init(); switch ($method) < case "POST": curl_setopt($curl, CURLOPT_POST, 1); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; case "PUT": curl_setopt($curl, CURLOPT_PUT, 1); break; default: if ($data) $url = sprintf("%s?%s", $url, http_build_query($data)); >// Optional Authentication: curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curl, CURLOPT_USERPWD, "username:password"); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); return $result; >
If you have a url and your php supports it, you could just call file_get_contents :
$response = file_get_contents('http://example.com/path/to/api/call?param1=5');
if $response is JSON, use json_decode to turn it into PHP array :
$response = json_decode($response);
if $response is XML, use simple_xml class:
$response = new SimpleXMLElement($response);
Use Guzzle. It’s a «PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services». Working with Guzzle is much easier than working with cURL.
Here’s an example from the Web site:
$client = new GuzzleHttp\Client(); $res = $client->get('https://api.github.com/user', [ 'auth' => ['user', 'pass'] ]); echo $res->getStatusCode(); // 200 echo $res->getHeader('content-type'); // 'application/json; charset=utf8' echo $res->getBody(); // json()); // Outputs the JSON decoded data
CURL is the simplest way to go. Here is a simple call
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "THE URL TO THE SERVICE"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA); $result = curl_exec($ch); print_r($result); curl_close($ch);
Php curl call api Code Example, $data_array = array( «customer» => $user[‘User’][‘customer_id’], «payment» => array( «number» => $this->request->data[‘account’], «routing» => $this->request->data
Calling the rest api in php
Hi Good evening currently working on flipkart / snapdeal rest api in which we have to curl the data . In command prompt its working fine and give me desired output . But now i want to call that in code and unable to do that . Kindly help me out for that . Api contain the token and token id . here my command which is working fine.
curl -H "Fk-Affiliate-Id:abhishekbh" -H "Fk-Affiliate-Token:2dacb05681b8481eb65201283dac2630" "https://affiliate-api.flipkart.net/affiliate/1.0/feeds/abhishebh/category/7jv.json?expiresAt=1489539219049&sig=ad5ef1af7f41d68d9f8f1c1ae85e20b6"
Here is the php code to send request using curl.
$s = curl_init(); curl_setopt($s,CURLOPT_URL,'https://affiliate-api.flipkart.net/affiliate/1.0/feeds/abhishekbh/category/7jv.json?expiresAt=1489539219049&sig=ad5ef1af7f41d68d9f8f1c1ae85e20b6'); curl_setopt($s,CURLOPT_HTTPHEADER,array('Fk-Affiliate-Id:abhishekbh', 'Fk-Affiliate-Token:2dacb05681b8481eb65291283dac2630')); curl_setopt($s,CURLOPT_HEADER,true); $result = curl_exec($s); echo "
";print_r($result);echo "";
How to call an api via php and get a json file from it, You can also use file_get_contentto get API data. $json = file_get_contents(«$url») Share Follow answered Oct 5, 2017 at 5:38 M ArfanM Arfan 4,09744 gold badges2727 silver badges4444 bronze badges Add a comment | 1
How to call an api via php and get a json file from it
I want to check all of the requested urls and if the url contains «video» folder in it, redirect it to an API file. then the API gives me a json files which only contains «respond:true» or «respond:false». In case of having respond:true in the json file the url must be showed and if the json file contains respond:false a predefined simple 403 page must be showed to the user.
I know that the fist part is possible with a simple code in .htaccess file like this:
RewriteRule ^your/special/folder/ /specified/url [R,L]
But I don’t know how to do the second part. I mean how to get the result of API, which is in form of a json file and check it.
GET REQUEST
$url = 'http://example.com/api/products'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HTTPGET, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response_json = curl_exec($ch); curl_close($ch); $response=json_decode($response_json, true);
POST REQUEST
$postdata = array( 'name' => 'Arfan' ); $url = "https://example.com/api/user/create"; $curl = curl_init($url); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); $json_response = curl_exec($curl); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl);
You can also use file_get_content to get API data.
$json = file_get_contents("$url")
You can execute second part (Calling API and response): Call API using curl and process based on its response:
$ch = curl_init(); curl_setopt($ch, CURLOPT_POST, false); curl_setopt($ch, CURLOPT_URL, "api_url_here"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $api_response_json = curl_exec($ch); curl_close($ch); //convert json to PHP array for further process $api_response_arr = json_decode($api_response_json); if($api_response_arr['respond'] == true )< //code for success here >else < // code for false here >
Please note: JSON response from API is depend on API Response , If API is giving response in json format ( can be based on params also ).
Call api with php Code Example, Follow. GREPPER; SEARCH SNIPPETS; FAQ; USAGE DOCS ; INSTALL GREPPER; Log In; All Languages >> PHP >> WordPress >> call api with php >> PHP >> WordPress >> call api with php
PHP REST client API call
I’m wondering, is there an easy way to perform a REST API GET call? I’ve been reading about cURL, but is that a good way to do it?
I also came across php://input but I have no idea how to use it. Does anyone have an example for me?
I don’t need advanced API client stuff, I just need to perform a GET call to a certain URL to get some JSON data that will be parsed by the client.
There are multiple ways to make REST client API call:
CURL is the simplest and good way to go. Here is a simple call
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA); $result = curl_exec($ch); print_r($result); curl_close($ch);
It’s a «PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services». Working with Guzzle is much easier than working with cURL.
Here’s an example from the Web site:
$client = new GuzzleHttp\Client(); $res = $client->get('https://api.github.com/user', [ 'auth' => ['user', 'pass'] ]); echo $res->getStatusCode(); // 200 echo $res->getHeader('content-type'); // 'application/json; charset=utf8' echo $res->getBody(); // json()); // Outputs the JSON decoded data
If you have a url and your php supports it, you could just call file_get_contents:
$response = file_get_contents('http://example.com/path/to/api/call?param1=5');
if $response is JSON, use json_decode to turn it into php array:
$response = json_decode($response);
If you are using Symfony there’s a great rest client bundle that even includes all of the ~100 exceptions and throws them instead of returning some meaningless error code + message.
try < $restClient = new RestClient(); $response = $restClient->get('http://www.someUrl.com'); $statusCode = $response->getStatusCode(); $content = $response->getContent(); > catch(OperationTimedOutException $e) < // do something >
Httpful is a simple, chainable, readable PHP library intended to make speaking HTTP sane. It lets the developer focus on interacting with APIs instead of sifting through curl set_opt pages and is an ideal PHP REST client .
- Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, and OPTIONS)
- Custom Headers
- Automatic «Smart» Parsing
- Automatic Payload Serialization
- Basic Auth
- Client Side Certificate Auth
- Request «Templates»
Send off a GET request. Get automatically parsed JSON response.
The library notices the JSON Content-Type in the response and automatically parses the response into a native PHP object.
$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D"; $response = \Httpful\Request::get($uri)->send(); echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";
You can use file_get_contents if the fopen wrappers are enabled. See: http://php.net/manual/en/function.file-get-contents.php
If they are not, and you cannot fix that because your host doesn’t allow it, cURL is a good method to use.
$result = file_get_contents( $url );
Execute php code on api Code Example, // Method: POST, PUT, GET etc // Data: array(«param» => «value») ==> index.php?param=value function CallAPI($method, $url, …