Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 67 ยท APIs

The HTTP Client and Consuming APIs in Laravel

Call other APIs from Laravel with the Http facade - JSON, headers and tokens, timeouts, retries, throw, concurrent pools, macros and Http::fake in tests.

Sooner or later your app has to talk to somebody else's server: a payment provider, a weather service, a GitHub webhook, another microservice of your own. Plain PHP can do it with cURL or file_get_contents, but you end up writing the same boilerplate again and again: encode the body, set headers, check the status, decode the response, handle timeouts.

Laravel's HTTP client is a fluent wrapper around the Guzzle library that does this for you. In this lesson you will make requests, send authentication, set timeouts, retry flaky calls, send several requests at once, define reusable clients with macros, and, most importantly, replace the network with Http::fake() so your tests are fast and never touch a real server. The real facade is shown read-only. The runnable examples build a small fake client so you can see retries and fakes work. For the other side of the conversation, see building JSON APIs.

Making requests

PHP
use Illuminate\Support\Facades\Http;

$response = Http::get('https://api.example.com/users/1');

$response->status();        // 200
$response->ok();            // true for 200
$response->successful();    // true for any 2xx
$response->failed();        // true for 4xx or 5xx
$response->body();          // raw string
$response->json();          // decoded array
$response->json('data.name');   // dot notation, null if missing
$response->collect('data');     // a Laravel collection

Notice that a 404 or 500 does not throw by default: you get a response and must check it. That is a deliberate design, because many APIs use 4xx codes to carry meaning.

Sending data is just as short:

PHP
$response = Http::post('https://api.example.com/orders', [
    'sku' => 'book-1',
    'quantity' => 2,
]);

post() sends the array as JSON by default. Use asForm() for application/x-www-form-urlencoded, attach() for file uploads, and get($url, ['page' => 2]) to add a query string.

Headers, tokens and a base URL

Chain configuration methods before the verb:

PHP
$response = Http::baseUrl('https://api.example.com/v1')
    ->withToken(config('services.example.key'))     // Authorization: Bearer ...
    ->withHeaders(['X-Request-Source' => 'tutorials'])
    ->acceptJson()
    ->get('/users', ['page' => 2]);

Keep API keys in .env, expose them through config/services.php, and read them with config() (configuration and environments). Never hard-code secrets.

Timeouts

By default the client waits up to 30 seconds. For a web request, that is far too long: your own user is waiting behind it. Set limits explicitly:

PHP
Http::connectTimeout(3)   // seconds to establish the connection
    ->timeout(5)          // seconds for the whole request
    ->get($url);

When a timeout is hit the client throws Illuminate\Http\Client\ConnectionException. Slow third-party calls usually belong in a queued job, not in a controller.

Failing loudly with throw

Add ->throw() to turn a 4xx or 5xx into a RequestException, so you cannot forget to check:

PHP
$order = Http::withToken($token)
    ->post('https://api.example.com/orders', $payload)
    ->throw()                     // exception on error status
    ->json();

// or react to the failure first
Http::get($url)
    ->onError(fn ($response) => logger()->warning('API failed', ['status' => $response->status()]))
    ->throw();

Retries

Networks are unreliable: a request may fail once and succeed a moment later. retry() repeats a request when it fails with a connection error or a 4xx/5xx status (with throw() it throws only after the last attempt):

PHP
$response = Http::retry(3, 200)          // up to 3 attempts, 200 ms between them
    ->timeout(5)
    ->get('https://api.example.com/report')
    ->throw();

// only retry server errors and connection problems, never a 422 or a 404
Http::retry(3, 200, when: function (Throwable $e, $request) {
    return $e instanceof ConnectionException
        || ($e instanceof RequestException && $e->response->serverError());
})->post($url, $data);

Be careful with POST: retrying a request that creates something (a charge, an order) can create it twice if the first attempt actually succeeded but the answer was lost. Send an idempotency key header when the provider supports it, and retry only safe, repeatable calls blindly.

flowchart LR
    A["Attempt 1"] -- "500" --> W1["wait"]
    W1 --> B["Attempt 2"]
    B -- "timeout" --> W2["wait"]
    W2 --> C["Attempt 3"]
    C -- "200" --> OK["Response"]
    C -- "500" --> E["throw RequestException"]

retry(3) makes up to three attempts; the last failure is reported when throw() is used.

The stand-in below is a small client with a fake network behind it. It plays back a list of responses (a "sequence"), retries on server errors, and records what happened, without sleeping.

PHP A fake HTTP client with retries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In real Laravel the default retry() also retries 4xx responses when combined with throw(), which is why the when: callback above matters. Here we simplified to "retry server errors only", the behavior you usually want.

Several requests at once

Http::pool() sends requests concurrently, so three calls that take one second each finish in about one second instead of three:

PHP
use Illuminate\Http\Client\Pool;

$responses = Http::pool(fn (Pool $pool) => [
    $pool->as('user')->get('https://api.example.com/users/1'),
    $pool->as('orders')->get('https://api.example.com/users/1/orders'),
    $pool->as('invoices')->get('https://api.example.com/users/1/invoices'),
]);

$user = $responses['user']->json();
$orders = $responses['orders']->json();

Name each request with as() so you can read the result by key. Inside a pool, configure each request on $pool, not on Http.

Macros and reusable clients

If you call the same API in many places, put its setup in one place. A macro adds your own method to the Http facade (register it in AppServiceProvider::boot()):

PHP
Http::macro('github', function () {
    return Http::baseUrl('https://api.github.com')
        ->withToken(config('services.github.token'))
        ->acceptJson()
        ->timeout(5)
        ->retry(2, 200);
});

$repos = Http::github()->get('/user/repos')->throw()->json();

For larger integrations, wrap the client in your own class (GitHubClient) that returns typed arrays or DTOs and hides the HTTP details from the rest of your app. Controllers then depend on your class, which is easy to fake in tests (architecture patterns).

Faking requests in tests

Tests must never call real APIs: they would be slow, flaky and could cost money. Http::fake() intercepts every request and returns what you define:

PHP
use Illuminate\Support\Facades\Http;

it('shows the weather', function () {
    Http::fake([
        'api.weather.test/*' => Http::response(['temp' => 21], 200),
        '*' => Http::response('', 500),            // everything else
    ]);

    $this->get('/weather/paris')->assertSee('21');

    Http::assertSent(fn ($request) => $request->url() === 'https://api.weather.test/current?city=paris');
    Http::assertSentCount(1);
});

// different answers for consecutive calls
Http::fake([
    'api.example.com/*' => Http::sequence()
        ->pushStatus(500)
        ->push(['ok' => true], 200),
]);

// make sure no test forgets to fake a call
Http::preventStrayRequests();

Http::preventStrayRequests() (put it in tests/Pest.php or a beforeEach) turns any unfaked request into an exception, so a missing fake fails loudly instead of quietly hitting the network. There is more on this in faking and mocking.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens by default when an API returns 404 or 500 to Http::get()?

    The client does not throw on error statuses by default. Check ok() or failed(), or add throw() to raise a RequestException.
  2. 2. Why is it risky to blindly retry a POST that creates an order?

    If the response is lost after the server already acted, a retry repeats the action. Use idempotency keys or retry only safe calls.
  3. 3. What does Http::pool() do?

    A pool runs requests at the same time, so the total time is roughly that of the slowest request instead of the sum.
  4. 4. What is Http::preventStrayRequests() for?

    It guarantees tests never reach the real network by accident. A missing fake becomes a loud failure.
  5. 5. Why set connectTimeout() and timeout() on outgoing calls?

    Explicit short timeouts protect your app from slow dependencies. Move long calls to a queued job.

Summary

  • Http::get/post/put/delete return a response with status(), json(), ok(), failed().
  • Configure with baseUrl, withToken, withHeaders, acceptJson; keep keys in config.
  • Set connectTimeout() and timeout(); use throw() to fail loudly.
  • retry() repeats flaky calls; retry only safe or idempotent requests.
  • Http::pool() runs requests concurrently; macros and wrapper classes keep integrations tidy.
  • In tests use Http::fake(), Http::sequence(), assertions and preventStrayRequests().

Next: Livewire Basics