Symfony2 - How to perform an external Request

59,545

Solution 1

I'd suggest using CURL:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'www.someapi.com?param1=A&param2=B');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); // Assuming you're requesting JSON
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);

// If using JSON...
$data = json_decode($response);

Note: The php on your web server must have the php5-curl library installed.

Assuming the API request is returning JSON data, this page may be useful.

This doesn't use any code that is specific to Symfony2. There may well be a bundle that can simplify this process for you, but if there is I don't know about it.

Solution 2

Symfony doesn't have a built-in service for this, but this is a perfect opportunity to create your own, using the dependency injection framework. What you can do here is write a service to manage the external call. Let's call the service "http".

First, write a class with a performRequest() method:

namespace MyBundle\Service;

class Http
{    
    public function performRequest($siteUrl)
    {
        // Code to make the external request goes here
        // ...probably using cUrl
    }
}

Register it as a service in app/config/config.yml:

services:
    http:
        class: MyBundle\Service\Http

Now your controller has access to a service called "http". Symfony manages a single instance of this class in the "container", and you can access it via $this->get("http"):

class MyController
{
    $response = $this->get("http")->performRequest("www.something.com");

    ...
}

Solution 3

Best client that I know is: http://docs.guzzlephp.org/en/latest/

There is already bundle that integrates it into Symfony2 project: https://github.com/8p/GuzzleBundle

$client   = $this->get('guzzle.client');

// send an asynchronous request.
$request = $client->createRequest('GET', 'http://httpbin.org', ['future' => true]);
// callback
$client->send($request)->then(function ($response) {
    echo 'I completed! ' . $response;
});

// optional parameters
$response = $client->get('http://httpbin.org/get', [
    'headers' => ['X-Foo-Header' => 'value'],
    'query'   => ['foo' => 'bar']
]);
$code = $response->getStatusCode();
$body = $response->getBody();

// json response
$response = $client->get('http://httpbin.org/get');
$json = $response->json();

// extra methods
$response = $client->delete('http://httpbin.org/delete');
$response = $client->head('http://httpbin.org/get');
$response = $client->options('http://httpbin.org/get');
$response = $client->patch('http://httpbin.org/patch');
$response = $client->post('http://httpbin.org/post');
$response = $client->put('http://httpbin.org/put');

More info can be found on: http://docs.guzzlephp.org/en/latest/index.html

Solution 4

https://github.com/sensio/SensioBuzzBundle seems to be what you are looking for.

It implements the Kris Wallsmith buzz library to perform HTTP requests.

I'll let you read the doc on the github page, usage is pretty basic:

$buzz = $this->container->get('buzz');

$response = $buzz->get('http://google.com');

echo $response->getContent();

Solution 5

Symfony does not have its own rest client, but as you already mentioned there are a couple of bundles. This one is my prefered one:

https://github.com/CircleOfNice/CiRestClientBundle

$restClient = $this->container->get('ci.restclient');

$restClient->get('http://www.someUrl.com');
$restClient->post('http://www.someUrl.com', 'somePayload');
$restClient->put('http://www.someUrl.com', 'somePayload');
$restClient->delete('http://www.someUrl.com');
$restClient->patch('http://www.someUrl.com', 'somePayload');

$restClient->head('http://www.someUrl.com');
$restClient->options('http://www.someUrl.com', 'somePayload');
$restClient->trace('http://www.someUrl.com');
$restClient->connect('http://www.someUrl.com');

You send the request via

$response = $restclient->get($url); 

and get a Symfony response object. Then you can get the status code via

$httpCode = $response-> getStatusCode();

Your code would look like:

$restClient = $this->container->get('ci.restclient');
if ($restClient->get('http://www.yourUrl.com')->getStatusCode !== 200) {
    // no error
} else {
    // error
}
Share:
59,545
ElPiter
Author by

ElPiter

Sr. Software Engineer at Vesta Healthcare

Updated on April 15, 2020

Comments

  • ElPiter
    ElPiter about 4 years

    Using Symfony2, I need to access an external API based on HTTPS.

    How can I call an external URI and manage the response to "play" with it. For example, to render a success or a failure message?

    I am thinking in something like (note that performRequest is a completely invented method):

    $response = $this -> performRequest("www.someapi.com?param1=A&param2=B");
    
    if ($response -> getError() == 0){
        // Do something good
    }else{
        // Do something too bad
    }
    

    I have been reading about Buzz and other clients. But I guess that Symfony2 should be able to do it by its own.