Doing HTTP requests FROM Laravel to an external API

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

    As of Laravel v7.X, the framework now comes with a minimal API wrapped around the Guzzle HTTP client. It provides an easy way to make get, post, put, patch, and delete requests using the HTTP Client:

    use Illuminate\Support\Facades\Http;
    
    $response = Http::get('http://test.com');
    $response = Http::post('http://test.com');
    $response = Http::put('http://test.com');
    $response = Http::patch('http://test.com');
    $response = Http::delete('http://test.com');
    

    You can manage responses using the set of methods provided by the Illuminate\Http\Client\Response instance returned.

    $response->body() : string;
    $response->json() : array;
    $response->status() : int;
    $response->ok() : bool;
    $response->successful() : bool;
    $response->serverError() : bool;
    $response->clientError() : bool;
    $response->header($header) : string;
    $response->headers() : array;
    

    Please note that you will, of course, need to install Guzzle like so:

    composer require guzzlehttp/guzzle
    

    There are a lot more helpful features built-in and you can find out more about these set of the feature here: https://laravel.com/docs/7.x/http-client

    This is definitely now the easiest way to make external API calls within Laravel.

提交回复
热议问题