Welcome to HowToShipIt — practical how-to guides for developers: code, AI tools, and servers, explained step by step.

Laravel HTTP Client: The Complete Guide to Calling APIs the Right Way (2026)

Every Laravel app talks to another service sooner or later: a payment gateway, a weather API, your own microservice, a webhook receiver. The Laravel HTTP client is the framework’s built-in, fluent wrapper around Guzzle for exactly that job — and if you are still hand-rolling cURL calls or newing up a raw Guzzle client in every controller, you are doing more work than you need to. This guide walks through the whole client, from your first Http::get() to retries, concurrent pools, reusable macros, and tests that never touch the network. Every behaviour below is verified against the official Laravel 13.x documentation, checked on 20 November 2026.

What the Laravel HTTP client actually is

The Laravel HTTP client is not a new HTTP library. It is a thin, expressive layer over Guzzle, Laravel’s default HTTP transport since the client shipped in Laravel 7. Guzzle ships with Laravel, so there is nothing to install — you import the Http facade and start calling APIs.

What you get over raw Guzzle is Laravel-flavoured ergonomics: chainable methods, sensible defaults, first-class testing fakes, and exceptions that behave the way a Laravel developer expects. The client is available through Illuminate\Support\Facades\Http, and every request returns an Illuminate\Http\Client\Response object with helpers for the status, body, and JSON payload.

One design decision shapes everything else in this guide: unlike Guzzle’s default behaviour, the Laravel HTTP client does not throw exceptions on 4xx or 5xx responses. A 404 is a response you inspect, not an exception you catch. You opt into throwing explicitly with throw(), which we will cover below.

Your first request with the Laravel HTTP client

The simplest possible call is one line:

use Illuminate\Support\Facades\Http;

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

All six standard verbs are available as facade methods: head, get, post, put, patch, and delete. The response object gives you everything you need to read the result:

$response->body();       // string
$response->json();       // array (or a single key: $response->json('data'))
$response->object();     // stdClass
$response->collect();    // Illuminate\Support\Collection
$response->status();     // int, e.g. 200
$response->successful(); // true for 2xx
$response->failed();     // true for 4xx and 5xx
$response->clientError();// true for 4xx
$response->serverError();// true for 5xx
$response->header('X-Rate-Limit'); // a single response header

The response object also implements PHP’s ArrayAccess interface, so you can reach straight into JSON payloads:

return Http::get('https://api.example.com/users/1')['name'];

And if you prefer explicit status checks, the client ships with one method per status code — ok(), created(), notFound(), unauthorized(), tooManyRequests(), serverError(), and the rest. Use tooManyRequests() in your rate-limit handling instead of comparing raw integers; it reads better six months from now.

While you are developing, Http::dd() dumps the outgoing request and stops execution — the fastest way to see exactly what headers and payload your code is about to send:

return Http::dd()->get('https://api.example.com/users');

Sending data: JSON, forms, files, and raw bodies

POST, PUT, and PATCH accept an array as their second argument. By default the data is sent as JSON with an application/json content type:

$response = Http::post('https://api.example.com/users', [
    'name' => 'Steve',
    'role' => 'Network Administrator',
]);

GET requests take query parameters the same way — pass an array as the second argument and Laravel builds the query string for you. Or use withQueryParameters() when you want the parameters set before the call, for example when chaining retry() in front of it.

For the other content types you will meet in the wild:

// Form-encoded data (application/x-www-form-urlencoded)
Http::asForm()->post('https://api.example.com/users', [
    'name' => 'Sara',
]);

// A raw request body, with an explicit content type
Http::withBody(base64_encode($photo), 'image/jpeg')
    ->post('https://api.example.com/photo');

// A multipart file upload
Http::attach(
    'attachment', file_get_contents('photo.jpg'), 'photo.jpg'
)->post('https://api.example.com/attachments');

attach() also accepts a stream resource instead of file contents, and a fourth argument for per-file headers — useful when an API wants a specific content type on the part itself. If you are uploading a large file, pass the fopen() resource rather than loading the whole file into memory with file_get_contents().

Finally, the client supports URI templates, so you can build URLs from named parameters instead of concatenating strings:

Http::withUrlParameters([
    'endpoint' => 'https://api.example.com',
    'version'  => 'v1',
    'id'       => 42,
])->get('{+endpoint}/{version}/users/{id}');

Headers and authentication

Headers go on with withHeaders(), and the method merges with any headers already set. To replace them entirely, use replaceHeaders():

$response = Http::withHeaders([
    'X-First'  => 'foo',
    'X-Second' => 'bar',
])->post('https://api.example.com/users', [
    'name' => 'Taylor',
]);

Two convenience methods set the Accept header: accept('application/json') for any content type, and acceptJson() for the common JSON case. Authentication has its own shortcuts too:

// Bearer token
Http::withToken($token)->post('https://api.example.com/data');

// Basic auth
Http::withBasicAuth('[email protected]', 'secret')->post(/* ... */);

// Digest auth
Http::withDigestAuth('[email protected]', 'secret')->post(/* ... */);

Read tokens and credentials from config — config('services.github.token') — never hard-code them in a controller. If your app talks to an API that issues short-lived tokens, the retry callback in the next section is the clean place to refresh them.

Timeouts and retries that survive real APIs

This is the section that separates a demo from a production integration. By default the Laravel HTTP client waits up to 30 seconds for a response, and up to 10 seconds to connect. A 30-second wait inside a web request is a timeout your users will feel, so set explicit values on every call that matters:

$response = Http::timeout(3)->get('https://api.example.com/users');
$response = Http::connectTimeout(3)->get('https://api.example.com/users');

If the timeout is exceeded, Laravel throws an Illuminate\Http\Client\ConnectionException. Catch that specifically — it means the network failed, which is a different problem from an API returning a 500.

Retries are one method call. retry(3, 100) attempts the request up to three times, sleeping 100 milliseconds between attempts, and only retries when a client or server error occurs:

$response = Http::retry(3, 100)->post('https://api.example.com/data');

You can pass a closure instead of a fixed delay to get exponential backoff, or an array of delays where the array’s length sets the number of attempts:

// Exponential backoff: 100ms, 200ms, 300ms...
Http::retry(3, fn (int $attempt, Exception $exception) => $attempt * 100)
    ->post('https://api.example.com/data');

// Array form: two retries, sleeping 100ms then 200ms
Http::retry([100, 200])->post('https://api.example.com/data');

The third argument is a callback that decides whether a retry should actually happen. This is where you put real-world judgement — retry on connection failures, not on a 422 validation error that will fail identically the second time:

use Illuminate\Http\Client\PendingRequest;
use Throwable;

$response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) {
    return $exception instanceof ConnectionException;
})->post('https://api.example.com/data');

The same callback lets you mutate the request before the next attempt. The classic use is refreshing an expired token after a 401:

use Illuminate\Http\Client\RequestException;

$response = Http::withToken($this->getToken())
    ->retry(2, 0, function (Throwable $exception, PendingRequest $request) {
        if (! $exception instanceof RequestException
            || $exception->response->status() !== 401) {
            return false;
        }

        $request->withToken($this->getNewToken());

        return true;
    })
    ->post('https://api.example.com/data');

One gotcha: when retries are exhausted, Laravel throws a RequestException by default. Pass throw: false to get the last response back instead — but note that a ConnectionException is still thrown even with throw: false, because there is no response to return:

$response = Http::retry(3, 100, throw: false)->post('https://api.example.com/data');

Error handling without the guesswork

Because the client does not throw on error statuses, your normal flow is a status check, not a try/catch:

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

if ($response->successful()) {
    return $response->json();
}

Log::error('API request failed: '.$response->body());

When you do want exceptions, throw() throws a RequestException on any client or server error, and returns the response when there is none — so it chains neatly:

return Http::post('https://api.example.com/users', $data)
    ->throw()
    ->json();

The throwIf(), throwUnless(), throwIfStatus(), throwUnlessStatus(), throwIfServerError(), and throwIfClientError() variants let you throw only in the cases you care about. The exception carries a public $response property, so your handler can inspect the status and body that caused it.

Two smaller details worth knowing. First, RequestException messages are truncated to 120 characters when logged or reported, to stop a giant error body flooding your logs. You can raise that limit or disable truncation globally in bootstrap/app.php with RequestException::truncateAt(240) or RequestException::dontTruncate(), or per request with Http::truncateExceptionsAt(240). Second, Laravel fires three events around every request — RequestSending, ResponseReceived, and ConnectionFailed — which is the clean hook if you want to log every outgoing call or feed an observability tool without touching every call site.

Concurrent requests: pool() vs batch()

Five sequential API calls at 400ms each cost two seconds of wall-clock time. The Laravel HTTP client runs them concurrently instead, with two APIs for two different jobs.

pool() is the simple one: give it a closure that returns an array of requests, and you get an array of responses back in the same order. Name requests with as() to access them by key instead of index:

use Illuminate\Http\Client\Pool;

$responses = Http::pool(fn (Pool $pool) => [
    $pool->as('user')->get('https://api.example.com/user/42'),
    $pool->as('orders')->get('https://api.example.com/orders', ['user_id' => 42]),
    $pool->as('recommendations')->get('https://api.recommend.com/for/42'),
]);

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

Cap the number of requests in flight at once with the concurrency argument — five is a sensible default for most APIs, and it keeps you from hammering a small provider with fifty simultaneous connections:

$responses = Http::pool(fn (Pool $pool) => [
    // ...
], concurrency: 5);

Two pool behaviours catch people out. First, pool() cannot be chained with withHeaders() or middleware — set headers on each request inside the pool instead. Second, if a pooled request fails at the connection level (a timeout, a DNS failure), that entry in the results array is a ConnectionException instance, not a Response — so check with instanceof Throwable before calling response methods on it.

batch() is the pool’s more capable sibling. It takes the same closure, but adds lifecycle callbacks — before, progress, then, catch, and finally — and you start it explicitly with send():

use Illuminate\Http\Client\Batch;

$responses = Http::batch(fn (Batch $batch) => [
    $batch->get('https://api.example.com/first'),
    $batch->get('https://api.example.com/second'),
    $batch->get('https://api.example.com/third'),
])->progress(function (Batch $batch, int|string $key, Response $response) {
    // One request just finished...
})->then(function (Batch $batch, array $results) {
    // Everything succeeded...
})->catch(function (Batch $batch, int|string $key, $response) {
    // A request failed...
})->finally(function (Batch $batch, array $results) {
    // Always runs, whatever happened...
})->send();

Batch also has a defer() method: the requests run only after the current application’s HTTP response has been sent to the user, which keeps the page feeling fast while the API work still happens. And if you try to add requests to a batch after send() has started it, Laravel throws a BatchInProgressException — so build the whole batch before you send it.

Rule of thumb: pool() when you need a handful of results back right now; batch() when you need progress reporting, per-request failure handling, or deferred execution.

Reusable clients: baseUrl, macros, and global defaults

Scattering Http::withToken(...)->timeout(5) across twenty controllers is how an integration rots. Centralise it. The lightest option is baseUrl(), which prefixes every relative path you pass afterwards:

$response = Http::baseUrl('https://api.github.com')
    ->withToken(config('services.github.token'))
    ->get('/user/repos');

Macros go one step further: define a named client once in your AppServiceProvider‘s boot() method and call it anywhere:

use Illuminate\Support\Facades\Http;

public function boot(): void
{
    Http::macro('github', function () {
        return Http::baseUrl('https://api.github.com')
            ->withToken(config('services.github.token'))
            ->timeout(5)
            ->connectTimeout(2);
    });
}

// Anywhere in your app:
$response = Http::github()->get('/user/repos');

For settings that should apply to every outgoing request in the application, use Http::globalOptions() — typically in the same provider — to set Guzzle options app-wide, and globalRequestMiddleware() / globalResponseMiddleware() to attach middleware to all requests and responses, for example a consistent User-Agent header. Per-request middleware is available too, via withRequestMiddleware() and withResponseMiddleware(), and withOptions() passes any Guzzle option (such as debug => true) through to the underlying client.

If you prefer dependency injection over facades, register the configured client as a singleton in a service provider and type-hint Illuminate\Http\Client\PendingRequest in your service class. Either way, the point is the same: the base URL, token, timeout, and retry policy live in exactly one place.

Testing without touching the real API

The Laravel HTTP client has the best testing story of any part of the framework’s HTTP stack. Http::fake() stubs responses by URL pattern, with * as a wildcard:

use Illuminate\Support\Facades\Http;

Http::fake([
    'github.com/*' => Http::response(['foo' => 'bar'], 200, $headers),
    'google.com/*' => Http::response('Hello World', 200, $headers),
]);

Simple stubs can be a string, an array, or an integer status code. URLs that match no pattern are really executed — unless you add a '*' fallback pattern, or call Http::preventStrayRequests(), which throws a StrayRequestException for any unfaked request instead of letting it reach the internet. Put preventStrayRequests() in your base TestCase and allow specific hosts with allowStrayRequests() only where a test genuinely needs the network. That one line is the difference between a test suite that is fast and deterministic and one that fails because a third-party API had a bad morning.

Sequences let you test retry and failure paths. Each request consumes the next response in order:

Http::fake([
    'github.com/*' => Http::sequence()
        ->push('Hello World', 200)
        ->push(['foo' => 'bar'], 200)
        ->pushStatus(404),
]);

When the sequence runs out, further requests throw — unless you add a whenEmpty() default. There are dedicated helpers for failure testing too: Http::failedConnection() makes the client throw a ConnectionException, and Http::failedRequest() builds a RequestException you can throw from a mock.

Finally, assert on what was actually sent. Http::assertSent() takes a closure over the recorded request, assertNotSent() and assertSentCount() cover the negative and the count, assertNothingSent() proves silence, and Http::recorded() returns every request/response pair so you can inspect them directly:

Http::fake();

Http::withHeaders(['X-First' => 'foo'])->post('https://api.example.com/users', [
    'name' => 'Taylor',
]);

Http::assertSent(function (Request $request) {
    return $request->hasHeader('X-First', 'foo')
        && $request->url() == 'https://api.example.com/users'
        && $request['name'] == 'Taylor';
});

7 mistakes that break Laravel HTTP client integrations

1. No timeout anywhere. The 30-second default is a safety net, not a policy. A slow payment provider will hold your request open for half a minute and queue up workers behind it. Set timeout() and connectTimeout() on every integration.

2. Retrying non-idempotent requests blindly. retry() re-sends the whole request. Retrying a GET is harmless; retrying a charge or an order creation can double-charge a customer. Only retry requests that are safe to repeat, or gate retries with the when callback.

3. Hard-coding tokens and secrets. A token in a controller ends up in version control eventually. Read everything from config/services.php and .env, and rotate a leaked key immediately — do not just delete the commit.

4. Calling five APIs one after another. If the calls are independent, pool() them. Sequential calls are the most common performance bug in Laravel integrations, and the fix is usually five lines.

5. Treating a 429 like a 500. A rate limit is the API telling you to slow down, not to fail. Check tooManyRequests(), read the Retry-After header, and back off — ideally in a queued job rather than in the request that is already running.

6. Testing against the live API. Tests that hit the real internet are slow, flaky, and occasionally destructive. Fake the client, assert on the recorded requests, and turn on preventStrayRequests() so a forgotten fake fails loudly in CI instead of quietly in production.

7. Logging full responses and request bodies. API responses contain tokens, personal data, and occasionally secrets. Log the status, the URL, and a correlation ID — and remember that RequestException messages are truncated to 120 characters by default for exactly this reason.

Putting it together: a production-ready service class

Here is the shape most integrations should end up in — a small service class, a macro for the client, and a queued job for anything slow:

namespace App\Services;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class GithubService
{
    public function userRepos(string $username): array
    {
        try {
            return Http::github()
                ->retry(3, 100, fn ($e) => $e instanceof ConnectionException)
                ->get("/users/{$username}/repos")
                ->throw()
                ->json();
        } catch (ConnectionException $e) {
            Log::warning('GitHub unreachable', ['user' => $username]);
            return [];
        }
    }
}

The macro holds the base URL, token, and timeouts. The retry only fires on connection failures. The exception handling distinguishes “the network failed” from “the API said no”. And if this call is slow or non-critical, move it into a queued job — your queue workers can retry it with backoff, and your users never wait on a third party. See our Laravel queue workers guide for the Supervisor setup that keeps those jobs running in production.

If the API you are calling needs its own authentication, the same pattern applies with Sanctum tokens on your side — our Laravel Sanctum setup guide covers the token side of that story.

Further Reading & References

Verified 20 November 2026. The official Laravel 13.x documentation is the authoritative source for every method in this post.

Leave a Comment