How to access a rest api in Symfony 3

How to access a rest api in Symfony 3

REST is an architecture style for designing networked applications. The idea is that, rather than using complex mechanisms such as CORBA, RPC or SOAP to connect between machines, simple HTTP is used to make calls between machines. In many ways, the World Wide Web itself, based on HTTP, can be viewed as a REST-based architecture. RESTful applications use HTTP requests to post data (create and/or update), read data (e.g., make queries), and delete data. Thus, REST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.

Because REST API’s use HTTP, they can be used by practically any programming language and easy to test (it’s a requirement of a REST API that the client and server are independent of each other allowing either to be coded in any language and improved upon supporting longevity and evolution).

A RESTful web service (also called a RESTful web API) is a web service implemented using HTTP and the principles of REST.

Basically, to access an api we need to execute a request in different formats according to the action that we want to achieve to an api endpoint (URL). With javascript, a simple XMLHttpRequest should do the trick, but with PHP there's another way to achieve it, named cURL.

cURL is a library that lets you make HTTP requests in PHP. Everything you need to know about it (and most other extensions) can be found in the PHP manual. In order to use PHP's cURL functions, although most PHP distributions has already installed cURL, if this is not your case, then you need to install the » libcURL package.

Using cURL by yourself

As mentioned before, cURL is the way to access a restful API from PHP.

The following method will help you to get the 

Note: the use of a library is recommended instead of plain cURL.

<?php
// 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 there was an error, the method will return false. You can read the following topic which explain how to handle errors using cURL.

Use a library (Unirest)

Using libraries instead of reinventing the wheel, that's why is better to use Unirest instead of write your own request functions as this library deal with a lot of common problems that you would face using plain cURL and it's maintained.

Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the open-source API Gateway Kong.

Features

  • Utility methods to call GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH requests.
  • Supports form parameters, file uploads and custom body entities.
  • Supports gzip.
  • Supports Basic, Digest, Negotiate, NTLM Authentication natively.
  • Customizable timeout.
  • Customizable default headers for every request (DRY).
  • Automatic JSON parsing into a native object for JSON responses.

Requirements

  • cURL
  • PHP 5.4+

To install Unirest PHP in your project, use composer. You can add the following line in your composer.json file :

{
    "require-dev": {
        "mashape/unirest-php": "2.*"
    }
}

Or execute the command in the console directly instead :

composer require mashape/unirest-php

Then you'll be able to use Unirest adding a simple use statement in the top of your class use Unirest;.

Using unirest

The following code shows a simple GET request to the /search endpoint of the Spotify API.

<?php

// search Songs of Frank Sinatra
$headers = array('Accept' => 'application/json');
$query = array('q' => 'Frank sinatra', 'type' => 'track');
        
$response = Unirest\Request::get('https://api.spotify.com/v1/search',$headers,$query);
// or use a plain text request
// $response = Unirest\Request::get('https://api.spotify.com/v1/search?q=Frank%20sinatra&type=track');

// Display the result
dump($response->body);

Note : if the code throws an error with "SSL certificate problem: unable to get local issuer certificate" when using Unirest with HTTPS API's, you may want to read the following article to learn how to solve it.

Body request Spotify API

The response variable has the following properties :

  • headers [Array] : Array with the header of the request (Date, Server etc).
  • body
  • code [Int] : Response code of the request.
  • raw_body : The raw content of the request.

Note that the body property was automatically converted to array as the API returns the response in JSON format. Read more about Unirest PHP in the official website.

Use the most common methods of unirest :

<?php

Unirest\Request::get($url, $headers = array(), $parameters = null)
Unirest\Request::post($url, $headers = array(), $body = null)
Unirest\Request::put($url, $headers = array(), $body = null)
Unirest\Request::patch($url, $headers = array(), $body = null)
Unirest\Request::delete($url, $headers = array(), $body = null)

Have fun !

Become a more social person