I am new to Symfony2 and I'm trying to send a
new Request()
to and external API. This is what I have but I don't know if it is correct use of the built in request/response library.
$request = new Request('https://myservice.com/apimethod?foo=bar', 'GET');
Can anyone tell me if this will return a response provided the API I'm trying to call exists?! If not, what am I doing wrong?
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);
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.
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
Use Guzzle from here.
Exemple:
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
echo $res->getStatusCode();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With