HTTP Client
- Introduction
- Making requests
- Concurrent requests
- Streaming responses
- Configuring the client
- Logging
- Testing
Introduction
Laravel provides an expressive HTTP client built on reqwest for making outgoing requests to external APIs and web services. It comes with sensible timeouts, configurable retries, and first-class error handling, and lets you fake outgoing responses in tests so your suite never touches the network.
All client functions and types live in the laravel::http::client module.
Making requests
Start a request with get, post, put, patch, delete, or head, chain any options, and await it:
1use laravel::http::client;23let response = client::get("https://example.com/users").await?;1use laravel::http::client;23let response = client::get("https://example.com/users").await?;
Awaiting sends the request and reads the entire response body. HTTP error statuses such as 404 or 500 still return Ok(response); ? fails only when the request could not be sent or timed out. To turn non-2xx statuses into errors automatically, see error handling.
You may send requests from handlers, console commands, queued jobs, and listeners. Inside tasks you spawn yourself, use laravel::task::spawn rather than tokio::spawn so the task inherits your application's HTTP client context.
Responses
Response provides the following methods for inspecting the server's reply:
| Method | Returns |
|---|---|
status() |
The StatusCode, which compares directly with integers (response.status() == 404). |
successful() |
true for 2xx status codes. |
redirect() |
true for 3xx status codes. |
failed() |
true for 4xx or 5xx status codes. |
client_error(), server_error() |
true for 4xx or 5xx status codes respectively. |
header("x-name") |
The header value as Option<&str>. |
headers() |
All response headers as &HeaderMap. |
url() |
The final URL after following redirects. |
bytes(), text() |
The response body as &Bytes or &str. |
json::<T>() |
The body deserialized from JSON as Result<T, Error>. |
Because the body is already buffered when the request resolves, json() and text() are synchronous. Decode JSON into your own struct or into serde_json::Value when you only need a few fields:
1use laravel::http::client;2use serde::Deserialize;34#[derive(Deserialize)]5pub struct GitHubUser {6 pub login: String,7 pub name: String,8}910let user: GitHubUser = client::get("https://api.github.com/users/taylorotwell")11 .await?12 .json()?;1314let raw: serde_json::Value = client::get("https://api.github.com/users/taylorotwell")15 .await?16 .json()?;1718let name = &raw["name"];1use laravel::http::client;2use serde::Deserialize;34#[derive(Deserialize)]5pub struct GitHubUser {6 pub login: String,7 pub name: String,8}910let user: GitHubUser = client::get("https://api.github.com/users/taylorotwell")11 .await?12 .json()?;1314let raw: serde_json::Value = client::get("https://api.github.com/users/taylorotwell")15 .await?16 .json()?;1718let name = &raw["name"];
Request data
Use json to send any Serialize value as a JSON request body:
1use laravel::http::client;2use serde_json::json;34client::post("https://example.com/users")5 .json(json!({ "name": "Steve", "role": "Network Administrator" }))6 .await?;1use laravel::http::client;2use serde_json::json;34client::post("https://example.com/users")5 .json(json!({ "name": "Steve", "role": "Network Administrator" }))6 .await?;
Use query to append query string parameters from key-value pairs, a json! object, or a Serialize struct (omitting None fields automatically):
1use laravel::http::client;2use serde::Serialize;3use serde_json::json;45client::get("https://example.com/users")6 .query([("name", "Taylor"), ("role", "admin")])7 .await?;89client::get("https://example.com/users")10 .query(json!({ "name": "Taylor", "page": 2 }))11 .await?;1213#[derive(Serialize)]14struct Search {15 q: String,16 page: u32,17 sort: Option<String>,18}1920client::get("https://example.com/search")21 .query(Search {22 q: "laravel".into(),23 page: 2,24 sort: None,25 })26 .await?;1use laravel::http::client;2use serde::Serialize;3use serde_json::json;45client::get("https://example.com/users")6 .query([("name", "Taylor"), ("role", "admin")])7 .await?;89client::get("https://example.com/users")10 .query(json!({ "name": "Taylor", "page": 2 }))11 .await?;1213#[derive(Serialize)]14struct Search {15 q: String,16 page: u32,17 sort: Option<String>,18}1920client::get("https://example.com/search")21 .query(Search {22 q: "laravel".into(),23 page: 2,24 sort: None,25 })26 .await?;
Because Rust arrays require uniform element types, use json! or a Serialize struct when mixing value types, or chain multiple .query(..) calls.
Use form to send URL-encoded form bodies, body to send a raw body with an explicit content type, or body_file to stream a file directly from disk without buffering it in memory:
1client::post("https://example.com/users")2 .form([("name", "Sara"), ("role", "Privacy Consultant")])3 .await?;45client::put("https://example.com/notes/1")6 .body("Remember the milk.", "text/plain")7 .await?;89client::put("https://example.com/backups/latest")10 .body_file("storage/app/backup.zip", "application/zip")11 .await?;1client::post("https://example.com/users")2 .form([("name", "Sara"), ("role", "Privacy Consultant")])3 .await?;45client::put("https://example.com/notes/1")6 .body("Remember the milk.", "text/plain")7 .await?;89client::put("https://example.com/backups/latest")10 .body_file("storage/app/backup.zip", "application/zip")11 .await?;
Attaching files
Send multipart file uploads with attach, passing the form field name and an Attachment. Any form fields are included alongside the attached files:
1use laravel::http::client::{self, Attachment};23client::post("https://example.com/reports")4 .attach("report", Attachment::from_path("storage/app/reports/q3.pdf"))5 .form([("quarter", "Q3")])6 .await?;1use laravel::http::client::{self, Attachment};23client::post("https://example.com/reports")4 .attach("report", Attachment::from_path("storage/app/reports/q3.pdf"))5 .form([("quarter", "Q3")])6 .await?;
Attachment::from_path streams a file from disk, resolving relative paths against your application's base path. Attachment::from_data(bytes, "avatar.png") sends in-memory bytes under the given filename. Content types are inferred from the filename unless you override the filename or MIME type using named and mime:
1Attachment::from_path("storage/app/exports/1234.tmp")2 .named("export.csv")3 .mime("text/csv")1Attachment::from_path("storage/app/exports/1234.tmp")2 .named("export.csv")3 .mime("text/csv")
You can also forward an incoming UploadedFile directly from a handler:
1use laravel::http::{UploadedFile, client};2use laravel::prelude::*;34#[laravel::input]5#[validate(authenticated)]6pub struct StorePhoto {7 #[validate(required, image)]8 photo: UploadedFile,9}1011pub async fn store(Valid(form): Valid<StorePhoto>) -> laravel::Result<Redirect> {12 client::post("https://storage.example.com/photos")13 .attach("photo", &form.photo)14 .await?;1516 Ok(Redirect::back())17}1use laravel::http::{UploadedFile, client};2use laravel::prelude::*;34#[laravel::input]5#[validate(authenticated)]6pub struct StorePhoto {7 #[validate(required, image)]8 photo: UploadedFile,9}1011pub async fn store(Valid(form): Valid<StorePhoto>) -> laravel::Result<Redirect> {12 client::post("https://storage.example.com/photos")13 .attach("photo", &form.photo)14 .await?;1516 Ok(Redirect::back())17}
Forward uploaded files inside the request handler itself rather than in a queued job or background task, because Laravel cleans up temporary uploads once the request completes.
Headers
Add individual headers with header or multiple headers at once with headers. Setting a header replaces any earlier header of the same name:
1use laravel::http::client;2use serde_json::json;34client::post("https://example.com/users")5 .headers([("x-tenant", "acme"), ("x-locale", "en")])6 .header("idempotency-key", "user-1234")7 .json(json!({ "name": "Taylor" }))8 .await?;1use laravel::http::client;2use serde_json::json;34client::post("https://example.com/users")5 .headers([("x-tenant", "acme"), ("x-locale", "en")])6 .header("idempotency-key", "user-1234")7 .json(json!({ "name": "Taylor" }))8 .await?;
Set the Accept header using accept or the accept_json shorthand:
1client::get("https://example.com/users").accept_json().await?;23client::get("https://example.com/reports/monthly")4 .accept("text/csv")5 .await?;1client::get("https://example.com/users").accept_json().await?;23client::get("https://example.com/reports/monthly")4 .accept("text/csv")5 .await?;
Authentication
You may authenticate outgoing requests using bearer tokens or HTTP basic authentication. To attach a bearer token to the request's Authorization header (Authorization: Bearer <token>), use the token method:
1use laravel::http::client;23let response = client::get("https://api.github.com/user")4 .token("your-token")5 .await?;1use laravel::http::client;23let response = client::get("https://api.github.com/user")4 .token("your-token")5 .await?;
You may specify HTTP basic authentication credentials using the basic_auth method, which Base64-encodes the username and password into an Authorization: Basic header:
1use laravel::http::client;23let response = client::get("https://example.com/user")5 .await?;1use laravel::http::client;23let response = client::get("https://example.com/user")5 .await?;
For APIs that expect a custom authentication scheme or an API key header, pass the header directly with header:
1use laravel::http::client;23let response = client::get("https://api.example.com/events")4 .header("x-api-key", "your-api-key")5 .await?;1use laravel::http::client;23let response = client::get("https://api.example.com/events")4 .header("x-api-key", "your-api-key")5 .await?;
In production applications, keep API keys and tokens out of your source code by storing them in a custom config section and injecting that section into your handler or service:
1// src/config/services.rs2use laravel::config::Section;34#[derive(Clone, Section)]5pub struct GitHub {6 #[env("GITHUB_TOKEN", required)]7 pub token: String,8}1// src/config/services.rs2use laravel::config::Section;34#[derive(Clone, Section)]5pub struct GitHub {6 #[env("GITHUB_TOKEN", required)]7 pub token: String,8}
1use laravel::config::Section;2use laravel::http::client;34use crate::config::services::GitHub;56pub async fn show(github: Section<GitHub>) -> laravel::Result<String> {7 let response = client::get("https://api.github.com/user")8 .token(&github.token)9 .await?;1011 Ok(response.text().into_owned())12}1use laravel::config::Section;2use laravel::http::client;34use crate::config::services::GitHub;56pub async fn show(github: Section<GitHub>) -> laravel::Result<String> {7 let response = client::get("https://api.github.com/user")8 .token(&github.token)9 .await?;1011 Ok(response.text().into_owned())12}
Laravel automatically marks Authorization, Proxy-Authorization, and Cookie header values as sensitive so they are redacted from debug output.
Base URLs and reusable requests
When calling the same API from multiple places, build a reusable PendingRequest template with client::base_url. Configure shared headers, tokens, and error handling once, then call get, post, and other verb methods with relative paths:
1use laravel::config::Section;2use laravel::http::client::{self, PendingRequest};3use laravel::prelude::*;4use serde_json::json;56use crate::config::services::GitHub;78fn github(config: &GitHub) -> PendingRequest {9 client::base_url("https://api.github.com")10 .token(&config.token)11 .accept_json()12 .ensure_successful()13}1415pub async fn show(config: Section<GitHub>) -> laravel::Result<Json<serde_json::Value>> {16 let github = github(&config);1718 let user: serde_json::Value = github.get("/user").await?.json()?;1920 let repositories: serde_json::Value = github21 .get("/user/repos")22 .query([("per_page", 100)])23 .await?24 .json()?;2526 Ok(Json(json!({ "user": user, "repositories": repositories })))27}1use laravel::config::Section;2use laravel::http::client::{self, PendingRequest};3use laravel::prelude::*;4use serde_json::json;56use crate::config::services::GitHub;78fn github(config: &GitHub) -> PendingRequest {9 client::base_url("https://api.github.com")10 .token(&config.token)11 .accept_json()12 .ensure_successful()13}1415pub async fn show(config: Section<GitHub>) -> laravel::Result<Json<serde_json::Value>> {16 let github = github(&config);1718 let user: serde_json::Value = github.get("/user").await?.json()?;1920 let repositories: serde_json::Value = github21 .get("/user/repos")22 .query([("per_page", 100)])23 .await?24 .json()?;2526 Ok(Json(json!({ "user": user, "repositories": repositories })))27}
URL parameters
Avoid interpolating user input into URLs with format!, since values like ../admin can alter the target path. Instead, use {name} placeholders and pass values via url_parameters, which percent-encodes each parameter as a single path segment:
1use laravel::http::client;23client::get("https://api.github.com/repos/{owner}/{repo}")4 .url_parameters([("owner", "laravel"), ("repo", "framework")])5 .await?;1use laravel::http::client;23client::get("https://api.github.com/repos/{owner}/{repo}")4 .url_parameters([("owner", "laravel"), ("repo", "framework")])5 .await?;
url_parameters accepts pairs or a Serialize struct like query. Use {+name} to expand a parameter without path-segment encoding, such as a full base URL.
Timeouts
By default, requests wait up to 30 seconds for the full response and 10 seconds to establish a connection. Override the limit on a single request with timeout:
1use laravel::http::client;2use laravel::prelude::*;34client::get("https://example.com").timeout(3.seconds()).await?;1use laravel::http::client;2use laravel::prelude::*;34client::get("https://example.com").timeout(3.seconds()).await?;
A timed-out request returns Error::Connection where error.is_timeout() is true. To change defaults application-wide, configure the client.
Retries
If you would like the HTTP client to automatically retry a request when a connection or non-2xx error occurs, use the retry method. Pass the maximum number of attempts along with either a fixed delay or a Backoff::exponential delay between attempts:
1use laravel::http::client::{self, Backoff};2use laravel::prelude::*;3use serde_json::json;45client::post("https://example.com/webhooks")6 .json(json!({ "event": "order.shipped" }))7 .retry(3, 100.milliseconds())8 .await?;910client::get("https://example.com")11 .retry(5, Backoff::exponential(100.milliseconds())) // 100ms, 200ms, 400ms, 800ms12 .await?;1use laravel::http::client::{self, Backoff};2use laravel::prelude::*;3use serde_json::json;45client::post("https://example.com/webhooks")6 .json(json!({ "event": "order.shipped" }))7 .retry(3, 100.milliseconds())8 .await?;910client::get("https://example.com")11 .retry(5, Backoff::exponential(100.milliseconds())) // 100ms, 200ms, 400ms, 800ms12 .await?;
If every attempt fails, the client returns the final attempt's error.
When a 429 or 503 response includes a Retry-After header (either seconds or an HTTP date), Laravel waits at least that long before retrying, provided the wait fits within the request's timeout or total_timeout. If the requested delay exceeds the remaining budget, the client stops retrying immediately and returns the error so you can handle it or re-queue the work.
Because each attempt uses its own timeout, multiple retries can exceed your handler's latency budget. Use total_timeout to cap the combined duration of all attempts and backoff delays:
1use laravel::http::client::{self, Backoff};2use laravel::prelude::*;34client::get("https://api.github.com/users/taylorotwell")5 .timeout(2.seconds())6 .retry(5, Backoff::exponential(200.milliseconds()))7 .total_timeout(5.seconds())8 .await?;1use laravel::http::client::{self, Backoff};2use laravel::prelude::*;34client::get("https://api.github.com/users/taylorotwell")5 .timeout(2.seconds())6 .retry(5, Backoff::exponential(200.milliseconds()))7 .total_timeout(5.seconds())8 .await?;
With total_timeout(5.seconds()), a 3-second Retry-After is honored when 3 seconds remain even though each individual attempt is capped at 2 seconds, while a 24-hour Retry-After fails immediately.
To retry only specific errors, pass a predicate to retry_when (attempts are 1-indexed):
1use laravel::http::client::{self, Error};2use laravel::prelude::*;34client::get("https://example.com")5 .retry(3, 100.milliseconds())6 .retry_when(|error, _attempt| matches!(error, Error::Connection(_)))7 .await?;1use laravel::http::client::{self, Error};2use laravel::prelude::*;34client::get("https://example.com")5 .retry(3, 100.milliseconds())6 .retry_when(|error, _attempt| matches!(error, Error::Connection(_)))7 .await?;
Retrying resends the same HTTP request. Only retry idempotent operations or requests protected by an idempotency key.
Error handling
By default, 4xx and 5xx responses return Ok(response). Call ensure_successful to convert any non-2xx status into Error::Status:
1use laravel::http::client;23let user: serde_json::Value = client::get("https://api.github.com/users/taylorotwell")4 .ensure_successful()5 .await?6 .json()?;1use laravel::http::client;23let user: serde_json::Value = client::get("https://api.github.com/users/taylorotwell")4 .ensure_successful()5 .await?6 .json()?;
You may also call response.ensure_successful()? after inspecting a response.
client::Error classifies failures into four variants:
| Variant | Cause |
|---|---|
Error::Connection |
No response arrived (unreachable host, TLS failure, or timeout). |
Error::Status |
Non-2xx status returned with ensure_successful or retry. Call error.response() to inspect it. |
Error::Decode |
json() could not deserialize the body into the target type. |
Error::Invalid |
Request could not be constructed (invalid URL or header). |
Match on client::Error to handle specific failure cases:
1use laravel::http::client::{self, Error};23let request = client::get("https://api.github.com/users/taylorotwell")4 .ensure_successful();56match request.await {7 Ok(response) => {8 // ...9 }10 Err(Error::Connection(error)) if error.is_timeout() => {11 // ...12 }13 Err(Error::Status(response)) if response.status() == 404 => {14 // ...15 }16 Err(error) => return Err(error.into()),17}1use laravel::http::client::{self, Error};23let request = client::get("https://api.github.com/users/taylorotwell")4 .ensure_successful();56match request.await {7 Ok(response) => {8 // ...9 }10 Err(Error::Connection(error)) if error.is_timeout() => {11 // ...12 }13 Err(Error::Status(response)) if response.status() == 404 => {14 // ...15 }16 Err(error) => return Err(error.into()),17}
When converted via ? into laravel::Error and returned from a handler, Laravel reports the failure and responds with 500, logging the URL and beginning of the response body:
1the HTTP request to https://api.example.com/users returned 404 Not Found: {"message":"Not found"}1the HTTP request to https://api.example.com/users returned 404 Not Found: {"message":"Not found"}
Concurrent requests
When you need responses from multiple independent endpoints, send them concurrently with task::try_join! by calling .send() to obtain each request's future:
1use laravel::http::client;2use laravel::task;34let (repository, release) = task::try_join!(5 client::get("https://api.github.com/repos/laravel/framework").send(),6 client::get("https://api.github.com/repos/laravel/framework/releases/latest").send(),7)?;1use laravel::http::client;2use laravel::task;34let (repository, release) = task::try_join!(5 client::get("https://api.github.com/repos/laravel/framework").send(),6 client::get("https://api.github.com/repos/laravel/framework/releases/latest").send(),7)?;
To bound concurrency across many requests, wrap them in a stream with .buffered(limit), which preserves input order:
1use laravel::http::client;2use laravel::stream::{self, StreamExt};34let responses: Vec<_> = stream::iter(["laravel", "symfony", "rust-lang"])5 .map(|org| {6 client::get("https://api.github.com/orgs/{org}")7 .url_parameters([("org", org)])8 .send()9 })10 .buffered(5)11 .collect()12 .await;1use laravel::http::client;2use laravel::stream::{self, StreamExt};34let responses: Vec<_> = stream::iter(["laravel", "symfony", "rust-lang"])5 .map(|org| {6 client::get("https://api.github.com/orgs/{org}")7 .url_parameters([("org", org)])8 .send()9 })10 .buffered(5)11 .collect()12 .await;
Streaming responses
For large downloads or streaming APIs (such as AI chat completions), call stream() instead of awaiting the full body into memory. stream() resolves to a StreamedResponse as soon as response headers arrive.
Call chunks() to iterate over the response body one chunk of bytes at a time:
1use laravel::http::client;2use laravel::stream::TryStreamExt;34let mut chunks = client::get("https://example.com/exports/orders.csv")5 .ensure_successful()6 .stream()7 .await?8 .chunks();910while let Some(chunk) = chunks.try_next().await? {11 // Process each chunk of bytes...12}1use laravel::http::client;2use laravel::stream::TryStreamExt;34let mut chunks = client::get("https://example.com/exports/orders.csv")5 .ensure_successful()6 .stream()7 .await?8 .chunks();910while let Some(chunk) = chunks.try_next().await? {11 // Process each chunk of bytes...12}
You can also pipe chunks() directly into file storage without buffering the download in memory:
1use laravel::http::client;2use laravel::storage;34let response = client::get("https://example.com/exports/orders.csv")5 .ensure_successful()6 .stream()7 .await?;89storage::disk("local")?10 .write_stream("exports/orders.csv", response.chunks())11 .await?;1use laravel::http::client;2use laravel::storage;34let response = client::get("https://example.com/exports/orders.csv")5 .ensure_successful()6 .stream()7 .await?;89storage::disk("local")?10 .write_stream("exports/orders.csv", response.chunks())11 .await?;
StreamedResponse exposes the same status(), header(), and status helpers as Response. Consume its body once using chunks() for raw bytes, events() for server-sent events, or into_response() to buffer the remainder into a regular Response.
While streaming, the request timeout applies per chunk read rather than to the entire stream, so active long-lived streams do not time out.
Server-sent events
Many AI and realtime APIs stream responses as server-sent events. Calling events() yields each completed event, exposing data() and json().
For example, this handler proxies a streaming OpenAI completion to the browser as an EventStream response:
1use laravel::config::Section;2use laravel::http::client;3use laravel::http::sse::EventStream;4use laravel::stream::TryStreamExt;5use serde_json::json;67use crate::config::services::OpenAi;89pub async fn chat(openai: Section<OpenAi>) -> laravel::Result<EventStream> {10 let mut events = client::post("https://api.openai.com/v1/chat/completions")11 .token(&openai.key)12 .json(json!({13 "model": "gpt-6.2-sol",14 "stream": true,15 "messages": [{ "role": "user", "content": "Write a haiku about Rust." }],16 }))17 .ensure_successful()18 .stream()19 .await?20 .events();2122 Ok(EventStream::channel(async move |sender| {23 while let Some(event) = events.try_next().await? {24 if event.data() == "[DONE]" {25 break;26 }2728 let delta: serde_json::Value = event.json()?;2930 if let Some(content) = delta["choices"][0]["delta"]["content"].as_str() {31 sender.send(content).await?;32 }33 }3435 Ok(())36 }))37}1use laravel::config::Section;2use laravel::http::client;3use laravel::http::sse::EventStream;4use laravel::stream::TryStreamExt;5use serde_json::json;67use crate::config::services::OpenAi;89pub async fn chat(openai: Section<OpenAi>) -> laravel::Result<EventStream> {10 let mut events = client::post("https://api.openai.com/v1/chat/completions")11 .token(&openai.key)12 .json(json!({13 "model": "gpt-6.2-sol",14 "stream": true,15 "messages": [{ "role": "user", "content": "Write a haiku about Rust." }],16 }))17 .ensure_successful()18 .stream()19 .await?20 .events();2122 Ok(EventStream::channel(async move |sender| {23 while let Some(event) = events.try_next().await? {24 if event.data() == "[DONE]" {25 break;26 }2728 let delta: serde_json::Value = event.json()?;2930 if let Some(content) = delta["choices"][0]["delta"]["content"].as_str() {31 sender.send(content).await?;32 }33 }3435 Ok(())36 }))37}
Configuring the client
All top-level helpers in laravel::http::client (client::get, client::post, client::base_url, and so on) dispatch requests through a single shared Client managed by your application. Sharing one Client lets requests across your application reuse pooled TCP and TLS connections, default timeouts, and request hooks.
Out of the box, the shared client uses the following defaults:
| Setting | Default |
|---|---|
timeout |
30 seconds |
connect_timeout |
10 seconds |
user_agent |
Laravel-Rust/<version> |
To customize these defaults across your entire application, construct a Client and register it with app.instance inside .with_services in src/app.rs:
1use laravel::http::client::Client;2use laravel::prelude::*;34Application::configure()5 .with_services(|app| {6 app.instance(7 Client::new()8 .timeout(10.seconds())9 .connect_timeout(5.seconds())10 .user_agent("Acme/1.0")11 .before_sending(|request| request.header("x-tenant", "acme"))12 .after_response(|response| {13 tracing::debug!(status = %response.status(), "API response");14 }),15 );16 })1use laravel::http::client::Client;2use laravel::prelude::*;34Application::configure()5 .with_services(|app| {6 app.instance(7 Client::new()8 .timeout(10.seconds())9 .connect_timeout(5.seconds())10 .user_agent("Acme/1.0")11 .before_sending(|request| request.header("x-tenant", "acme"))12 .after_response(|response| {13 tracing::debug!(status = %response.status(), "API response");14 }),15 );16 })
Registering the client with app.instance (rather than a lazy singleton) ensures it is already available if other services send HTTP requests while your application boots.
Lifecycle hooks let you inspect or transform every outgoing request and response passing through a client. before_sending hooks run in the order they were registered before each request is dispatched, and after_response hooks observe every response that comes back, including each retry attempt and faked responses in tests.
If a before_sending hook should only apply to a specific API, inspect request.url() before modifying the request:
1use laravel::http::client::Client;23let client = Client::new().before_sending(|request| {4 if request5 .url()6 .is_ok_and(|url| url.host_str() == Some("api.example.com"))7 {8 request.token("secret")9 } else {10 request11 }12});1use laravel::http::client::Client;23let client = Client::new().before_sending(|request| {4 if request5 .url()6 .is_ok_and(|url| url.host_str() == Some("api.example.com"))7 {8 request.token("secret")9 } else {10 request11 }12});
Transport options
When you need to configure the underlying reqwest transport directly (such as adding custom CA certificates, configuring mutual TLS or an HTTP proxy, or changing the redirect policy), pass a closure to configure_transport. The closure receives reqwest's ClientBuilder and returns the configured builder.
Import reqwest types from laravel::http::client::reqwest so your code always matches the version of reqwest bundled with Laravel:
1use laravel::http::client::{Client, reqwest};23let client = Client::new().configure_transport(|transport| {4 transport.redirect(reqwest::redirect::Policy::none())5});1use laravel::http::client::{Client, reqwest};23let client = Client::new().configure_transport(|transport| {4 transport.redirect(reqwest::redirect::Policy::none())5});
You may also call configure_transport on an individual request instead of the shared Client. Doing so creates an isolated connection pool for that request without affecting any other requests in your application.
Dedicated clients
Sometimes a single third-party integration needs its own User-Agent, stricter timeouts, custom TLS certificates, or a different redirect policy that you do not want applied to every outgoing request. In those cases, you can construct a dedicated Client and call get, post, base_url, and other request methods directly on it.
Because each Client maintains its own connection pool, avoid constructing a new one inside every request handler. Instead, wrap the dedicated Client in a service, register it once in src/app.rs, and inject it wherever it is needed:
1// src/services/reports.rs2use laravel::http::client::Client;3use laravel::prelude::*;45pub struct ReportsClient {6 http: Client,7}89impl ReportsClient {10 pub fn new() -> Self {11 Self {12 http: Client::new()13 .timeout(60.seconds())14 .user_agent("Acme Reports/1.0"),15 }16 }1718 pub async fn monthly(&self) -> laravel::Result<String> {19 let response = self20 .http21 .get("https://reports.example.com/monthly")22 .ensure_successful()23 .await?;2425 Ok(response.text().into_owned())26 }27}1// src/services/reports.rs2use laravel::http::client::Client;3use laravel::prelude::*;45pub struct ReportsClient {6 http: Client,7}89impl ReportsClient {10 pub fn new() -> Self {11 Self {12 http: Client::new()13 .timeout(60.seconds())14 .user_agent("Acme Reports/1.0"),15 }16 }1718 pub async fn monthly(&self) -> laravel::Result<String> {19 let response = self20 .http21 .get("https://reports.example.com/monthly")22 .ensure_successful()23 .await?;2425 Ok(response.text().into_owned())26 }27}
Register the service in src/app.rs, then resolve it in a handler with Inject:
1// src/app.rs2use laravel::prelude::*;34use crate::services::reports::ReportsClient;56Application::configure()7 .with_services(|app| {8 app.instance(ReportsClient::new());9 })1// src/app.rs2use laravel::prelude::*;34use crate::services::reports::ReportsClient;56Application::configure()7 .with_services(|app| {8 app.instance(ReportsClient::new());9 })
1use laravel::prelude::*;23use crate::services::reports::ReportsClient;45pub async fn show(reports: Inject<ReportsClient>) -> laravel::Result<String> {6 reports.monthly().await7}1use laravel::prelude::*;23use crate::services::reports::ReportsClient;45pub async fn show(reports: Inject<ReportsClient>) -> laravel::Result<String> {6 reports.monthly().await7}
Even when requests are sent through a dedicated Client, client::fake() still intercepts them automatically in your tests.
Logging
The HTTP client emits a debug log entry on the laravel::http::client target for every outgoing request, recording the method, URL, status, and duration_ms (or failure reason). Enable it with LOG_LEVEL=info,laravel::http::client=debug. Credentials and query strings are automatically stripped from logged URLs and error messages so API keys are never leaked.
When distributed tracing is enabled, each attempt of a request creates a span of its own and sends its own W3C traceparent header, so a retried request shows one span per attempt.
Testing
Faking responses
Call client::fake() in your tests to intercept outgoing requests and return fake responses without touching the network. By default, every request receives an empty 200 response:
1use laravel::http::client;2use laravel::testing::prelude::*;34#[laravel::test]5async fn shows_a_github_profile(app: Application) {6 let http = client::fake();78 app.get("/profile").await.assert_ok();910 http.assert_sent_count(1);11}1use laravel::http::client;2use laravel::testing::prelude::*;34#[laravel::test]5async fn shows_a_github_profile(app: Application) {6 let http = client::fake();78 app.get("/profile").await.assert_ok();910 http.assert_sent_count(1);11}
Keep the returned fake handle alive while exercising your application; dropping it restores live network requests. Each test's fake is isolated to its application, so concurrent tests never interfere.
Pass URL patterns to .with(..) to return custom responses. Patterns match anywhere in the URL and support * wildcards, matching in registration order. Responses can be status codes, strings, JSON values, or client::response() builders:
1use serde_json::json;23let http = client::fake()4 .with(5 "api.github.com/users/*",6 json!({ "login": "taylorotwell", "name": "Taylor Otwell" }),7 )8 .with(9 "api.stripe.com/*",10 client::response()11 .status(402)12 .json(json!({ "error": "card_declined" })),13 )14 .with("example.com/health", 503)15 .with("*", "Hello World");1use serde_json::json;23let http = client::fake()4 .with(5 "api.github.com/users/*",6 json!({ "login": "taylorotwell", "name": "Taylor Otwell" }),7 )8 .with(9 "api.stripe.com/*",10 client::response()11 .status(402)12 .json(json!({ "error": "card_declined" })),13 )14 .with("example.com/health", 503)15 .with("*", "Hello World");
Simulate network failures with client::failed_connection(), which returns Error::Connection:
1let http = client::fake().with("api.github.com/*", client::failed_connection());1let http = client::fake().with("api.github.com/*", client::failed_connection());
Faked requests still execute client hooks and retry logic, without sleeping between retries.
client::fake() intercepts requests sent through laravel::http::client. Third-party SDKs that create their own internal HTTP client bypass this fake.
Response sequences
Return a sequence of different responses for the same URL pattern using client::sequence(), which is useful for testing retries:
1use laravel::http::client;2use serde_json::json;34let http = client::fake().with(5 "api.github.com/*",6 client::sequence()7 .push(client::failed_connection())8 .push(503)9 .push(json!({ "login": "taylorotwell" })),10);1use laravel::http::client;2use serde_json::json;34let http = client::fake().with(5 "api.github.com/*",6 client::sequence()7 .push(client::failed_connection())8 .push(503)9 .push(json!({ "login": "taylorotwell" })),10);
Once a sequence is exhausted, further requests fail with Error::Invalid unless you configure a fallback with when_empty. Like push, when_empty accepts any fake response value: a status code, string, JSON value, client::response() builder, client::failed_connection(), or a callback closure:
1let http = client::fake().with(2 "api.github.com/*",3 client::sequence().push("Hello World").when_empty(4 client::response()5 .status(404)6 .json(json!({ "error": "not_found" })),7 ),8);1let http = client::fake().with(2 "api.github.com/*",3 client::sequence().push("Hello World").when_empty(4 client::response()5 .status(404)6 .json(json!({ "error": "not_found" })),7 ),8);
Fake callbacks
When the fake response depends on the incoming request, pass a closure to with. The closure receives a &Request and may return any fake response value (a status code, string, JSON value, or client::response() builder):
1use laravel::http::client::{self, Request};23let http = client::fake().with("api.example.com/*", |request: &Request| {4 if request.has_header("authorization", "Bearer secret") {5 2006 } else {7 4018 }9});1use laravel::http::client::{self, Request};23let http = client::fake().with("api.example.com/*", |request: &Request| {4 if request.has_header("authorization", "Bearer secret") {5 2006 } else {7 4018 }9});
You can inspect any part of the outgoing request inside the callback using the same Request methods available in assertions.
Faking streamed responses
When code calls stream(), fake response bodies arrive line by line. For example, this test fakes an OpenAI server-sent events stream for the chat handler:
1use laravel::http::client;2use laravel::testing::prelude::*;34#[laravel::test]5async fn chat_replies_stream(app: Application) {6 let http = client::fake().with(7 "api.openai.com/*",8 client::response()9 .header("content-type", "text/event-stream")10 .body(concat!(11 "data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n",12 "data: {\"choices\":[{\"delta\":{\"content\":\"lo!\"}}]}\n\n",13 "data: [DONE]\n\n",14 )),15 );1617 app.get("/chat")18 .await19 .assert_ok()20 .assert_see("data: Hel")21 .assert_see("data: lo!");22}1use laravel::http::client;2use laravel::testing::prelude::*;34#[laravel::test]5async fn chat_replies_stream(app: Application) {6 let http = client::fake().with(7 "api.openai.com/*",8 client::response()9 .header("content-type", "text/event-stream")10 .body(concat!(11 "data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n",12 "data: {\"choices\":[{\"delta\":{\"content\":\"lo!\"}}]}\n\n",13 "data: [DONE]\n\n",14 )),15 );1617 app.get("/chat")18 .await19 .assert_ok()20 .assert_see("data: Hel")21 .assert_see("data: lo!");22}
Inspecting requests
The fake records every outgoing request while active, including retries. Use assert_sent to verify that at least one recorded request matches a predicate:
1use laravel::http::Method;23http.assert_sent(|request| {4 request.method() == Method::POST5 && request.url() == "https://example.com/users"6 && request.has_header("x-tenant", "acme")7 && request.data()["name"] == "Taylor"8});910http.assert_not_sent(|request| request.url().contains("/posts"));11http.assert_sent_count(5);12http.assert_nothing_sent();1use laravel::http::Method;23http.assert_sent(|request| {4 request.method() == Method::POST5 && request.url() == "https://example.com/users"6 && request.has_header("x-tenant", "acme")7 && request.data()["name"] == "Taylor"8});910http.assert_not_sent(|request| request.url().contains("/posts"));11http.assert_sent_count(5);12http.assert_nothing_sent();
Request exposes the full outgoing request inside both assert_sent predicates and fake callbacks:
| Method | Description |
|---|---|
method() |
The HTTP Method (GET, POST, etc.) |
url() |
The full resolved URL, including base URL and query string |
header(name) |
A header's text value as Option<&str> |
has_header(name, |
Whether the header was sent with the given value |
headers() |
All outgoing headers as a HeaderMap |
body() |
The raw body bytes (&[u8]) |
data() |
Parsed JSON, form, or multipart text fields as serde_json::Value |
json::<T>() |
Deserializes a JSON body into a typed struct |
files() |
Attached multipart files (&[SentFile]) |
has_file(name, |
Whether a multipart file was attached with the given field and filename |
For example, check multipart uploads with has_file:
1http.assert_sent(|request| request.has_file("report", "q3.pdf"));1http.assert_sent(|request| request.has_file("report", "q3.pdf"));
For custom assertions, sent() returns all recorded requests and recorded() returns (Request, Response) pairs:
1let [(request, response)] = http.recorded().try_into().unwrap();23assert_eq!(response.status(), 500);1let [(request, response)] = http.recorded().try_into().unwrap();23assert_eq!(response.status(), 500);
Stray requests
Unmatched requests receive an empty 200 by default. Call prevent_stray_requests to fail any unexpected request with Error::Invalid:
1use serde_json::json;23let http = client::fake()4 .with("api.github.com/*", json!({ "login": "taylorotwell" }))5 .prevent_stray_requests();1use serde_json::json;23let http = client::fake()4 .with("api.github.com/*", json!({ "login": "taylorotwell" }))5 .prevent_stray_requests();
To allow specific live hosts (such as a local test server) while still blocking all other stray requests, use allow_stray_requests:
1use serde_json::json;23let http = client::fake()4 .with("api.github.com/*", json!({ "login": "taylorotwell" }))5 .allow_stray_requests(["http://127.0.0.1:5000/*"]);1use serde_json::json;23let http = client::fake()4 .with("api.github.com/*", json!({ "login": "taylorotwell" }))5 .allow_stray_requests(["http://127.0.0.1:5000/*"]);