首頁  >  文章  >  後端開發  >  Laravel 中的多個 API 與 HTTP 請求

Laravel 中的多個 API 與 HTTP 請求

WBOY
WBOY原創
2024-08-18 06:45:02934瀏覽

今天給大家分享,如何在Laravel中呼叫多個api
我們現在承諾可以從客戶端呼叫多個 api(vue、react、js...)。如果你使用 Promise.all([...]),它會回傳多個 Promise

好了,我們走吧

首先,你可以安裝專案Laravel 11

第二個,我們可以在web.php或控制器、服務、..

中設定它

範例:我在 web.php 檔案中寫程式碼,幫忙測試

use Illuminate\Support\Facades\Http;
use GuzzleHttp\Promise\Utils;
use GuzzleHttp\Exception\ConnectException;
use Illuminate\Http\Client\Pool;

Route::get('multiple-request', function() {
    $responses = Utils::all([
        'foo' => Http::async()->get('https://jsonplaceholder.typicode.com/todos/1')->then(function ($response) {
            // you can check data, after then return it
            return $response;
        }),
        'bar' => Http::async()->get('https://jsonplaceholder.typicode.com/todos/2')->then(function ($response) {
             // you can check data, after then return it
            return $response;
        }),
        'baz' => Http::async()->get('https://jsonplaceholder.typicode.com/todos/3')->then(function ($response) {
            // you can check data, after then return it
            return $response;
        }),
    ])->wait();

    // you need check data here
    $fooOk = $responses['foo']->ok();
    $barSuccessful = $responses['bar']->successful();
    $connectionFailed = $responses['baz'] instanceof ConnectException;

    return [
        'foo' => $responses['foo']->ok() ? $responses['foo']->json() : 'Request to foo failed',
        'bar' => $responses['bar']->successful() ? $responses['bar']->json() : 'Request to bar failed',
        'baz' => $responses['baz']->ok() ? $responses['baz']->json() : 'Request to baz failed',
    ];
});

當您要求 url : http://127.0.0.1/multiple-request 時,它會傳回資料

Multiple API in Laravel with HTTP Requests

好的,或是你可以使用 Http::pool ,請求 api

Route::get('multiple-request-using-pool', function() {

        $responses = Http::pool(fn (Pool $pool) => [
            $pool->get('https://jsonplaceholder.typicode.com/todos/1'),
            $pool->get('https://jsonplaceholder.typicode.com/todos/2'),
            $pool->get('https://jsonplaceholder.typicode.com/todos/3'),
        ]);

        $responses[0]->ok();
        $responses[1]->successful();
        // Kiểm tra và lấy nội dung từ các phản hồi
        $data = [
            'todo_1' => $responses[0]->ok() ? $responses[0]->json() : 'Request to todo 1 failed',
            'todo_2' => $responses[1]->successful() ? $responses[1]->json() : 'Request to todo 2 failed',
            'todo_3' => $responses[2]->ok() ? $responses[2]->json() : 'Request to todo 3 failed',
        ];

        return response()->json($data);

});

回傳資料:

Multiple API in Laravel with HTTP Requests

文章:Laravel 中的多個 API 和 HTTP 請求

以上是Laravel 中的多個 API 與 HTTP 請求的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn