How to send a request to an external API How to send a request to an external API symfony symfony

How to send a request to an external API


In Symfony2, the Request class represents an HTTP request made to your site. Basically, if you go to www.yoursite.com/someaction Symfony instantiates aSymfony\Component\HttpFoundation\Request object. This object contains methods that you can use to examine the HTTP request (such as seeing if it contains GET or POST variables.)

This is a good explanation of Symfony and HTTP fundamentals. I also recommend looking at the source code for Request to see exactly what it can do.

In order to achieve what you're trying to do in your example, you'd need to use cURL. I personally use a wrapper class on top of cURL that you can find here.

Hope this helps.


https://github.com/CircleOfNice/CiRestClientBundle

It's the easiest way to send a request to an external API. It provides all http methods as functions and is easy to use.

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

If you want to use rest clients just to CRUD entities then I think you should have a look at

https://github.com/CircleOfNice/DoctrineRestDriver

which helps you to get rid of manually sending requests and mapping responses because Doctrine is doing the job for you.

// Sends a GET request to http://$driverUrl/@TableAnnotation/1 and returns a valid MyEntity Entity$entity = $em->find("Some\Namespace\MyEntity", 1);


Someone else answered a question like this: https://stackoverflow.com/a/10715549/2306587

You don't have to rely on cURL to make an external request. There is a Symfony-Bundle who can handle that: http://knpbundles.com/sonata-project/SonataGoutteBundle