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?
12 Answers
You can access any REST API with PHPs cURL Extension. However, the API Documentation (Methods, Parameters etc.) must be provided by your Client!
Example:
// 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; } 18If you have a url and your php supports it, you could just call file_get_contents:
$response = file_get_contents('); 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); 3Use 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(' [ 'auth' => ['user', 'pass'] ]); echo $res->getStatusCode(); // 200 echo $res->getHeader('content-type'); // 'application/json; charset=utf8' echo $res->getBody(); // {"type":"User"...' var_export($res->json()); // Outputs the JSON decoded data 3CURL 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); 0Use HTTPFUL
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.
Httpful includes...
- 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"
Ex.
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 = ""; $response = \Httpful\Request::get($uri)->send(); echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n"; 1You will need to know if the REST API you are calling supports GET or POST, or both methods. The code below is something that works for me, I'm calling my own web service API, so I already know what the API takes and what it will return. It supports both GET and POST methods, so the less sensitive info goes into the URL (GET), and the info like username and password is submitted as POST variables. Also, everything goes over the HTTPS connection.
Inside the API code, I encode an array I want to return into json format, then simply use PHP command echo $my_json_variable to make that json string availabe to the client.
So as you can see, my API returns json data, but you need to know (or look at the returned data to find out) what format the response from the API is in.
This is how I connect to the API from the client side:
$processed = FALSE; $ERROR_MESSAGE = ''; // ************* Call API: $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "" . $email_to_subscribe); curl_setopt($ch, CURLOPT_POST, 1);// set post data to true curl_setopt($ch, CURLOPT_POSTFIELDS,"username=myname&password=mypass"); // post data curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $json = curl_exec($ch); curl_close ($ch); // returned json string will look like this: {"code":1,"data":"OK"} // "code" may contain an error code and "data" may contain error string instead of "OK" $obj = json_decode($json); if ($obj->{'code'} == '1') { $processed = TRUE; }else{ $ERROR_MESSAGE = $obj->{'data'}; } ... if (!$processed && $ERROR_MESSAGE != '') { echo $ERROR_MESSAGE; } BTW, I also tried to use file_get_contents() method as some of the users here suggested, but that din't work well for me. I found out the curl method to be faster and more reliable.
You can go with POSTMAN, an application who makes APIs easy. Fill request fields and then it will generate code for you in different languages. Just click code on the right side and select your prefered language.
1You can use file_get_contents to issue any http POST/PUT/DELETE/OPTIONS/HEAD methods, in addition to the GET method as the function name suggests.
How to post data in PHP using file_get_contents?
1There are plenty of clients actually. One of them is Pest - check this out. And keep in mind that these REST calls are simple http request with various methods: GET, POST, PUT and DELETE.
0as @Christoph Winkler mentioned this is a base class for achieving it:
curl_helper.php
// This class has all the necessary code for making API calls thru curl library class CurlHelper { // This method will perform an action/method thru HTTP/API calls // Parameter description: // Method= POST, PUT, GET etc // Data= array("param" => "value") ==> index.php?param=value public static function perform_http_request($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; } } Then you can always include the file and use it e.g.: any.php
require_once("curl_helper.php"); ... $action = "GET"; $url = "" echo "Trying to reach ..."; echo $url; $parameters = array("param" => "value"); $result = CurlHelper::perform_http_request($action, $url, $parameters); echo print_r($result) 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.
I love the interface:
try { $restClient = new RestClient(); $response = $restClient->get('); $statusCode = $response->getStatusCode(); $content = $response->getContent(); } catch(OperationTimedOutException $e) { // do something } Works for all http methods.
If you are open to use third party tools you'd have a look at this one:
This is a completely new way to work with APIs.
First of all you define an entity which is defining the structure of incoming and outcoming data and annotate it with datasources:
/* * @Entity * @DataSource\Select("") * @DataSource\Insert("") * @DataSource\Select("") * @DataSource\Fetch("") * @DataSource\Delete("") */ class Product { private $name; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } } Now it's pretty easy to communicate with the REST API:
$product = new Product(); $product->setName('test'); // sends an API request POST ... $em->persist($product); $em->flush(); $product->setName('newName'); // sends an API request UPDATE ... $em->flush(); 1