Doing HTTP requests FROM Laravel to an external API

前端 未结 7 1730
隐瞒了意图╮
隐瞒了意图╮ 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:13

    Updated on March 21 2019

    Add GuzzleHttp package using composer require guzzlehttp/guzzle:~6.3.3

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

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

    Include below line in the top of the class where you are calling the API

    use GuzzleHttp\Client;
    

    Add below code for making the request

    $client = new Client();
    
        $res = $client->request('POST', 'http://www.exmple.com/mydetails', [
            'form_params' => [
                'name' => 'george',
            ]
        ]);
    
        if ($res->getStatusCode() == 200) { // 200 OK
            $response_data = $res->getBody()->getContents();
        }
    

提交回复
热议问题