Doing HTTP requests FROM Laravel to an external API

前端 未结 7 1717
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 09:59

What I want is get an object from an API with a HTTP (eg, jQuery\'s AJAX) request to an external api. How do I start? I did research on Mr Google but I can\'t find anything

7条回答
  •  一生所求
    2020-11-27 10:06

    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"...'
    }
    

提交回复
热议问题