Call a REST API in PHP

PhpRestWeb Services

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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;
}

Solution 2 - Php

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);

http://sg2.php.net/manual/en/simplexml.examples-basic.php

Solution 3 - Php

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();                 // {"type":"User"...'
var_export($res->json());             // Outputs the JSON decoded data

Solution 4 - Php

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);

Solution 5 - Php

Use 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 = "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";

Solution 6 - Php

You 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, "http://www.myapi.com/api.php?format=json&action=subscribe&email=" . $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.

Solution 7 - Php

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.

Solution 8 - Php

There 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.

Solution 9 - Php

You 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.

https://stackoverflow.com/questions/2445276/how-to-post-data-in-php-using-file-get-contents

Solution 10 - Php

as @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 = "api.server.com/model"
	echo "Trying to reach ...";
	echo $url;
	$parameters = array("param" => "value");
	$result = CurlHelper::perform_http_request($action, $url, $parameters);
    echo print_r($result)

Solution 11 - Php

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.

You should really check it: https://github.com/CircleOfNice/CiRestClientBundle

I love the interface:

try {
    $restClient = new RestClient();
    $response   = $restClient->get('http://www.someUrl.com');
    $statusCode = $response->getStatusCode();
    $content    = $response->getContent();
} catch(OperationTimedOutException $e) {
    // do something
}

Works for all http methods.

Solution 12 - Php

If you are open to use third party tools you'd have a look at this one: https://github.com/CircleOfNice/DoctrineRestDriver

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("http://www.myApi.com/products/{id}")
 * @DataSource\Insert("http://www.myApi.com/products")
 * @DataSource\Select("http://www.myApi.com/products/update/{id}")
 * @DataSource\Fetch("http://www.myApi.com/products")
 * @DataSource\Delete("http://www.myApi.com/products/delete/{id}")
 */
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 http://www.myApi.com/products ...
$em->persist($product);
$em->flush();

$product->setName('newName');
// sends an API request UPDATE http://www.myApi.com/products/update/1 ...
$em->flush();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichielView Question on Stackoverflow
Solution 1 - PhpChristoph WinklerView Answer on Stackoverflow
Solution 2 - PhpAndreas WongView Answer on Stackoverflow
Solution 3 - PhpcolanView Answer on Stackoverflow
Solution 4 - PhpBronchaView Answer on Stackoverflow
Solution 5 - PhpSomnath MulukView Answer on Stackoverflow
Solution 6 - PhpDerek GogolView Answer on Stackoverflow
Solution 7 - PhpXhuljoView Answer on Stackoverflow
Solution 8 - PhpdeadrunkView Answer on Stackoverflow
Solution 9 - PhpChuan MaView Answer on Stackoverflow
Solution 10 - Phpd1jhoni1bView Answer on Stackoverflow
Solution 11 - PhpTobiasView Answer on Stackoverflow
Solution 12 - PhpTobiasView Answer on Stackoverflow