PHP cURL

In general, we use cURL to communicate with API endpoints. Using cURL might not be the most pretty approach, but it definitely does the job. See the example below:

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

    $response = curl_exec($curl);

    curl_close($curl);

    return $response;
}

The above class could be enhanced, so it will use an object of type JSON, XML or just raw string data. To decode JSON and XML we need to use the fallowing functions:

if $response is JSON, use json_decode(...) to turn it into PHP associate array:

$response = json_decode($response);

If you call to XML data endpoint you can use SimpleXMLElement class to work with fetched data.

$response = new SimpleXMLElement($response);

For generic content, you could simply use file_get_contents()

$response = file_get_contents('http://example.com/path/to/api/call?param1=5');

If the REST endpoint returns an HTTP error status (e.g. 401), the file_get_contents function fails with a warning and returns null. If the body contains an error message, you cannot retrieve it.

PHP Community solutions

Guzzle (PHP class)

You could go around and build your own custom class based on cURL or perhaps use something that is already created and well documented. Introducing Guzzle – git repo. Read more about this fantastic solution here at https://docs.guzzlephp.org/en/stable/.

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

  • Simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc…
  • Can send both synchronous and asynchronous requests using the same interface.
  • Uses PSR-7 interfaces for requests, responses, and streams. This allows you to utilize other PSR-7 compatible libraries with Guzzle.
  • Abstracts away the underlying HTTP transport, allowing you to write environment and transport agnostic code; i.e., no hard dependency on cURL, PHP streams, sockets, or non-blocking event loops.
  • Middleware system allows you to augment and compose client behavior.
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
    'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type')[0];
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'

// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});
$promise->wait();

https://stackoverflow.com/questions/9802788/call-a-rest-api-in-php
https://docs.guzzlephp.org/en/stable/
https://github.com/guzzle/guzzle/tree/ee0a041b1760e6a53d2a39c8c34115adc2af2c79

0
Would love your thoughts, please comment.x
()
x