Doing HTTP requests FROM Laravel to an external API Doing HTTP requests FROM Laravel to an external API php php

Doing HTTP requests FROM Laravel to an external API


Based upon an answer of a similar question here:https://stackoverflow.com/a/22695523/1412268

Take a look at Guzzle

$client = new GuzzleHttp\Client();$res = $client->get('https://api.github.com/user', ['auth' =>  ['user', 'pass']]);echo $res->getStatusCode(); // 200echo $res->getBody(); // { "type": "User", ....


We can use package Guzzle in Laravel, it is a PHP HTTP client to send HTTP requests.

You can install Guzzle through composer

composer require guzzlehttp/guzzle:~6.0

Or you can specify Guzzle as a dependency in your project's existing composer.json

{   "require": {      "guzzlehttp/guzzle": "~6.0"   }}

Example code in laravel 5 using Guzzle as shown below,

use GuzzleHttp\Client;class yourController extends Controller {    public function saveApiData()    {        $client = new Client();        $res = $client->request('POST', 'https://url_to_the_api', [            'form_params' => [                'client_id' => 'test_id',                'secret' => 'test_secret',            ]        ]);        echo $res->getStatusCode();        // 200        echo $res->getHeader('content-type');        // 'application/json; charset=utf8'        echo $res->getBody();        // {"type":"User"...'}


You just want to call an external URL and use the results? PHP does this out of the box, if we're talking about a simple GET request to something serving JSON:

$json = json_decode(file_get_contents('http://host.com/api/stuff/1'), true);

If you want to do a post request, it's a little harder but there's loads of examples how to do this with curl.

So I guess the question is; what exactly do you want?