laravel-rust 0.1.4

Laravel for Rust: a full-stack Rust web framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
# HTTP Client

- [Introduction]#introduction
- [Making requests]#making-requests
    - [Responses]#responses
    - [Request data]#request-data
    - [Attaching files]#attaching-files
    - [Headers]#headers
    - [Authentication]#authentication
    - [Base URLs and reusable requests]#base-urls-and-reusable-requests
    - [URL parameters]#url-parameters
    - [Timeouts]#timeouts
    - [Retries]#retries
    - [Error handling]#error-handling
- [Concurrent requests]#concurrent-requests
- [Streaming responses]#streaming-responses
    - [Server-sent events]#server-sent-events
- [Configuring the client]#configuring-the-client
    - [Transport options]#transport-options
    - [Dedicated clients]#dedicated-clients
- [Logging]#logging
- [Testing]#testing
    - [Faking responses]#faking-responses
    - [Response sequences]#response-sequences
    - [Fake callbacks]#fake-callbacks
    - [Faking streamed responses]#faking-streamed-responses
    - [Inspecting requests]#inspecting-requests
    - [Stray requests]#stray-requests

<a name="introduction"></a>
## Introduction

Laravel provides an expressive HTTP client built on [reqwest](https://docs.rs/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.

<a name="making-requests"></a>
## Making requests

Start a request with `get`, `post`, `put`, `patch`, `delete`, or `head`, chain any options, and await it:

```rust
use laravel::http::client;

let 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](#error-handling).

You may send requests from handlers, console commands, queued jobs, and listeners. Inside tasks you spawn yourself, use [`laravel::task::spawn`](tasks.md#spawned-tasks) rather than `tokio::spawn` so the task inherits your application's HTTP client context.

<a name="responses"></a>
### 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:

```rust
use laravel::http::client;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct GitHubUser {
    pub login: String,
    pub name: String,
}

let user: GitHubUser = client::get("https://api.github.com/users/taylorotwell")
    .await?
    .json()?;

let raw: serde_json::Value = client::get("https://api.github.com/users/taylorotwell")
    .await?
    .json()?;

let name = &raw["name"];
```

<a name="request-data"></a>
### Request data

Use `json` to send any `Serialize` value as a JSON request body:

```rust
use laravel::http::client;
use serde_json::json;

client::post("https://example.com/users")
    .json(json!({ "name": "Steve", "role": "Network Administrator" }))
    .await?;
```

Use `query` to append query string parameters from key-value pairs, a `json!` object, or a `Serialize` struct (omitting `None` fields automatically):

```rust
use laravel::http::client;
use serde::Serialize;
use serde_json::json;

client::get("https://example.com/users")
    .query([("name", "Taylor"), ("role", "admin")])
    .await?;

client::get("https://example.com/users")
    .query(json!({ "name": "Taylor", "page": 2 }))
    .await?;

#[derive(Serialize)]
struct Search {
    q: String,
    page: u32,
    sort: Option<String>,
}

client::get("https://example.com/search")
    .query(Search {
        q: "laravel".into(),
        page: 2,
        sort: None,
    })
    .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:

```rust
client::post("https://example.com/users")
    .form([("name", "Sara"), ("role", "Privacy Consultant")])
    .await?;

client::put("https://example.com/notes/1")
    .body("Remember the milk.", "text/plain")
    .await?;

client::put("https://example.com/backups/latest")
    .body_file("storage/app/backup.zip", "application/zip")
    .await?;
```

<a name="attaching-files"></a>
### 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:

```rust
use laravel::http::client::{self, Attachment};

client::post("https://example.com/reports")
    .attach("report", Attachment::from_path("storage/app/reports/q3.pdf"))
    .form([("quarter", "Q3")])
    .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`:

```rust
Attachment::from_path("storage/app/exports/1234.tmp")
    .named("export.csv")
    .mime("text/csv")
```

You can also forward an incoming `UploadedFile` directly from a handler:

```rust
use laravel::http::{UploadedFile, client};
use laravel::prelude::*;

#[laravel::input]
#[validate(authenticated)]
pub struct StorePhoto {
    #[validate(required, image)]
    photo: UploadedFile,
}

pub async fn store(Valid(form): Valid<StorePhoto>) -> laravel::Result<Redirect> {
    client::post("https://storage.example.com/photos")
        .attach("photo", &form.photo)
        .await?;

    Ok(Redirect::back())
}
```

Forward uploaded files inside the request handler itself rather than in a queued job or background task, because Laravel [cleans up temporary uploads](requests.md#keeping-uploaded-files) once the request completes.

<a name="headers"></a>
### Headers

Add individual headers with `header` or multiple headers at once with `headers`. Setting a header replaces any earlier header of the same name:

```rust
use laravel::http::client;
use serde_json::json;

client::post("https://example.com/users")
    .headers([("x-tenant", "acme"), ("x-locale", "en")])
    .header("idempotency-key", "user-1234")
    .json(json!({ "name": "Taylor" }))
    .await?;
```

Set the `Accept` header using `accept` or the `accept_json` shorthand:

```rust
client::get("https://example.com/users").accept_json().await?;

client::get("https://example.com/reports/monthly")
    .accept("text/csv")
    .await?;
```

<a name="authentication"></a>
### 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:

```rust
use laravel::http::client;

let response = client::get("https://api.github.com/user")
    .token("your-token")
    .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:

```rust
use laravel::http::client;

let response = client::get("https://example.com/user")
    .basic_auth("taylor@laravel.com", "secret")
    .await?;
```

For APIs that expect a custom authentication scheme or an API key header, pass the header directly with `header`:

```rust
use laravel::http::client;

let response = client::get("https://api.example.com/events")
    .header("x-api-key", "your-api-key")
    .await?;
```

In production applications, keep API keys and tokens out of your source code by storing them in a [custom config section](configuration.md#your-own-config-sections) and injecting that section into your handler or service:

```rust
// src/config/services.rs
use laravel::config::Section;

#[derive(Clone, Section)]
pub struct GitHub {
    #[env("GITHUB_TOKEN", required)]
    pub token: String,
}
```

```rust
use laravel::config::Section;
use laravel::http::client;

use crate::config::services::GitHub;

pub async fn show(github: Section<GitHub>) -> laravel::Result<String> {
    let response = client::get("https://api.github.com/user")
        .token(&github.token)
        .await?;

    Ok(response.text().into_owned())
}
```

Laravel automatically marks `Authorization`, `Proxy-Authorization`, and `Cookie` header values as sensitive so they are redacted from debug output.

<a name="base-urls-and-reusable-requests"></a>
### 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:

```rust
use laravel::config::Section;
use laravel::http::client::{self, PendingRequest};
use laravel::prelude::*;
use serde_json::json;

use crate::config::services::GitHub;

fn github(config: &GitHub) -> PendingRequest {
    client::base_url("https://api.github.com")
        .token(&config.token)
        .accept_json()
        .ensure_successful()
}

pub async fn show(config: Section<GitHub>) -> laravel::Result<Json<serde_json::Value>> {
    let github = github(&config);

    let user: serde_json::Value = github.get("/user").await?.json()?;

    let repositories: serde_json::Value = github
        .get("/user/repos")
        .query([("per_page", 100)])
        .await?
        .json()?;

    Ok(Json(json!({ "user": user, "repositories": repositories })))
}
```

<a name="url-parameters"></a>
### 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:

```rust
use laravel::http::client;

client::get("https://api.github.com/repos/{owner}/{repo}")
    .url_parameters([("owner", "laravel"), ("repo", "framework")])
    .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.

<a name="timeouts"></a>
### 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`:

```rust
use laravel::http::client;
use laravel::prelude::*;

client::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](#configuring-the-client).

<a name="retries"></a>
### 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:

```rust
use laravel::http::client::{self, Backoff};
use laravel::prelude::*;
use serde_json::json;

client::post("https://example.com/webhooks")
    .json(json!({ "event": "order.shipped" }))
    .retry(3, 100.milliseconds())
    .await?;

client::get("https://example.com")
    .retry(5, Backoff::exponential(100.milliseconds())) // 100ms, 200ms, 400ms, 800ms
    .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](#timeouts) 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](#timeouts), multiple retries can exceed your handler's latency budget. Use `total_timeout` to cap the combined duration of all attempts and backoff delays:

```rust
use laravel::http::client::{self, Backoff};
use laravel::prelude::*;

client::get("https://api.github.com/users/taylorotwell")
    .timeout(2.seconds())
    .retry(5, Backoff::exponential(200.milliseconds()))
    .total_timeout(5.seconds())
    .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):

```rust
use laravel::http::client::{self, Error};
use laravel::prelude::*;

client::get("https://example.com")
    .retry(3, 100.milliseconds())
    .retry_when(|error, _attempt| matches!(error, Error::Connection(_)))
    .await?;
```

> [!WARNING]
> Retrying resends the same HTTP request. Only retry idempotent operations or requests protected by an idempotency key.

<a name="error-handling"></a>
### Error handling

By default, 4xx and 5xx responses return `Ok(response)`. Call `ensure_successful` to convert any non-2xx status into `Error::Status`:

```rust
use laravel::http::client;

let user: serde_json::Value = client::get("https://api.github.com/users/taylorotwell")
    .ensure_successful()
    .await?
    .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:

```rust
use laravel::http::client::{self, Error};

let request = client::get("https://api.github.com/users/taylorotwell")
    .ensure_successful();

match request.await {
    Ok(response) => {
        // ...
    }
    Err(Error::Connection(error)) if error.is_timeout() => {
        // ...
    }
    Err(Error::Status(response)) if response.status() == 404 => {
        // ...
    }
    Err(error) => return Err(error.into()),
}
```

When converted via `?` into `laravel::Error` and returned from a handler, Laravel [reports](errors.md) the failure and responds with `500`, logging the URL and beginning of the response body:

```text
the HTTP request to https://api.example.com/users returned 404 Not Found: {"message":"Not found"}
```

<a name="concurrent-requests"></a>
## Concurrent requests

When you need responses from multiple independent endpoints, send them concurrently with [`task::try_join!`](tasks.md#concurrent-operations) by calling `.send()` to obtain each request's future:

```rust
use laravel::http::client;
use laravel::task;

let (repository, release) = task::try_join!(
    client::get("https://api.github.com/repos/laravel/framework").send(),
    client::get("https://api.github.com/repos/laravel/framework/releases/latest").send(),
)?;
```

To bound concurrency across many requests, wrap them in a stream with `.buffered(limit)`, which preserves input order:

```rust
use laravel::http::client;
use laravel::stream::{self, StreamExt};

let responses: Vec<_> = stream::iter(["laravel", "symfony", "rust-lang"])
    .map(|org| {
        client::get("https://api.github.com/orgs/{org}")
            .url_parameters([("org", org)])
            .send()
    })
    .buffered(5)
    .collect()
    .await;
```

<a name="streaming-responses"></a>
## 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:

```rust
use laravel::http::client;
use laravel::stream::TryStreamExt;

let mut chunks = client::get("https://example.com/exports/orders.csv")
    .ensure_successful()
    .stream()
    .await?
    .chunks();

while let Some(chunk) = chunks.try_next().await? {
    // Process each chunk of bytes...
}
```

You can also pipe `chunks()` directly into [file storage](filesystem.md#streaming-large-files) without buffering the download in memory:

```rust
use laravel::http::client;
use laravel::storage;

let response = client::get("https://example.com/exports/orders.csv")
    .ensure_successful()
    .stream()
    .await?;

storage::disk("local")?
    .write_stream("exports/orders.csv", response.chunks())
    .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](#server-sent-events), or `into_response()` to buffer the remainder into a regular `Response`.

While streaming, the request [timeout](#timeouts) applies per chunk read rather than to the entire stream, so active long-lived streams do not time out.

<a name="server-sent-events"></a>
### Server-sent events

Many AI and realtime APIs stream responses as [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_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`](responses.md#event-streams) response:

```rust
use laravel::config::Section;
use laravel::http::client;
use laravel::http::sse::EventStream;
use laravel::stream::TryStreamExt;
use serde_json::json;

use crate::config::services::OpenAi;

pub async fn chat(openai: Section<OpenAi>) -> laravel::Result<EventStream> {
    let mut events = client::post("https://api.openai.com/v1/chat/completions")
        .token(&openai.key)
        .json(json!({
            "model": "gpt-6.2-sol",
            "stream": true,
            "messages": [{ "role": "user", "content": "Write a haiku about Rust." }],
        }))
        .ensure_successful()
        .stream()
        .await?
        .events();

    Ok(EventStream::channel(async move |sender| {
        while let Some(event) = events.try_next().await? {
            if event.data() == "[DONE]" {
                break;
            }

            let delta: serde_json::Value = event.json()?;

            if let Some(content) = delta["choices"][0]["delta"]["content"].as_str() {
                sender.send(content).await?;
            }
        }

        Ok(())
    }))
}
```

<a name="configuring-the-client"></a>
## 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`:

```rust
use laravel::http::client::Client;
use laravel::prelude::*;

Application::configure()
    .with_services(|app| {
        app.instance(
            Client::new()
                .timeout(10.seconds())
                .connect_timeout(5.seconds())
                .user_agent("Acme/1.0")
                .before_sending(|request| request.header("x-tenant", "acme"))
                .after_response(|response| {
                    tracing::debug!(status = %response.status(), "API response");
                }),
        );
    })
```

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:

```rust
use laravel::http::client::Client;

let client = Client::new().before_sending(|request| {
    if request
        .url()
        .is_ok_and(|url| url.host_str() == Some("api.example.com"))
    {
        request.token("secret")
    } else {
        request
    }
});
```

<a name="transport-options"></a>
### 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:

```rust
use laravel::http::client::{Client, reqwest};

let client = Client::new().configure_transport(|transport| {
    transport.redirect(reqwest::redirect::Policy::none())
});
```

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.

<a name="dedicated-clients"></a>
### 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](container.md), register it once in `src/app.rs`, and inject it wherever it is needed:

```rust
// src/services/reports.rs
use laravel::http::client::Client;
use laravel::prelude::*;

pub struct ReportsClient {
    http: Client,
}

impl ReportsClient {
    pub fn new() -> Self {
        Self {
            http: Client::new()
                .timeout(60.seconds())
                .user_agent("Acme Reports/1.0"),
        }
    }

    pub async fn monthly(&self) -> laravel::Result<String> {
        let response = self
            .http
            .get("https://reports.example.com/monthly")
            .ensure_successful()
            .await?;

        Ok(response.text().into_owned())
    }
}
```

Register the service in `src/app.rs`, then resolve it in a handler with `Inject`:

```rust
// src/app.rs
use laravel::prelude::*;

use crate::services::reports::ReportsClient;

Application::configure()
    .with_services(|app| {
        app.instance(ReportsClient::new());
    })
```

```rust
use laravel::prelude::*;

use crate::services::reports::ReportsClient;

pub async fn show(reports: Inject<ReportsClient>) -> laravel::Result<String> {
    reports.monthly().await
}
```

Even when requests are sent through a dedicated `Client`, `client::fake()` still intercepts them automatically in your [tests](#testing).

<a name="logging"></a>
## 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](tracing.md#traces-across-services) 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.

<a name="testing"></a>
## Testing

<a name="faking-responses"></a>
### 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:

```rust
use laravel::http::client;
use laravel::testing::prelude::*;

#[laravel::test]
async fn shows_a_github_profile(app: Application) {
    let http = client::fake();

    app.get("/profile").await.assert_ok();

    http.assert_sent_count(1);
}
```

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:

```rust
use serde_json::json;

let http = client::fake()
    .with(
        "api.github.com/users/*",
        json!({ "login": "taylorotwell", "name": "Taylor Otwell" }),
    )
    .with(
        "api.stripe.com/*",
        client::response()
            .status(402)
            .json(json!({ "error": "card_declined" })),
    )
    .with("example.com/health", 503)
    .with("*", "Hello World");
```

Simulate network failures with `client::failed_connection()`, which returns `Error::Connection`:

```rust
let http = client::fake().with("api.github.com/*", client::failed_connection());
```

Faked requests still execute client hooks and retry logic, without sleeping between retries.

> [!NOTE]
> `client::fake()` intercepts requests sent through `laravel::http::client`. Third-party SDKs that create their own internal HTTP client bypass this fake.

<a name="response-sequences"></a>
### Response sequences

Return a sequence of different responses for the same URL pattern using `client::sequence()`, which is useful for testing retries:

```rust
use laravel::http::client;
use serde_json::json;

let http = client::fake().with(
    "api.github.com/*",
    client::sequence()
        .push(client::failed_connection())
        .push(503)
        .push(json!({ "login": "taylorotwell" })),
);
```

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](#fake-callbacks):

```rust
let http = client::fake().with(
    "api.github.com/*",
    client::sequence().push("Hello World").when_empty(
        client::response()
            .status(404)
            .json(json!({ "error": "not_found" })),
    ),
);
```

<a name="fake-callbacks"></a>
### 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):

```rust
use laravel::http::client::{self, Request};

let http = client::fake().with("api.example.com/*", |request: &Request| {
    if request.has_header("authorization", "Bearer secret") {
        200
    } else {
        401
    }
});
```

You can inspect any part of the outgoing request inside the callback using the same [`Request` methods](#inspecting-requests) available in assertions.

<a name="faking-streamed-responses"></a>
### 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](#server-sent-events):

```rust
use laravel::http::client;
use laravel::testing::prelude::*;

#[laravel::test]
async fn chat_replies_stream(app: Application) {
    let http = client::fake().with(
        "api.openai.com/*",
        client::response()
            .header("content-type", "text/event-stream")
            .body(concat!(
                "data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n",
                "data: {\"choices\":[{\"delta\":{\"content\":\"lo!\"}}]}\n\n",
                "data: [DONE]\n\n",
            )),
    );

    app.get("/chat")
        .await
        .assert_ok()
        .assert_see("data: Hel")
        .assert_see("data: lo!");
}
```

<a name="inspecting-requests"></a>
### 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:

```rust
use laravel::http::Method;

http.assert_sent(|request| {
    request.method() == Method::POST
        && request.url() == "https://example.com/users"
        && request.has_header("x-tenant", "acme")
        && request.data()["name"] == "Taylor"
});

http.assert_not_sent(|request| request.url().contains("/posts"));
http.assert_sent_count(5);
http.assert_nothing_sent();
```

`Request` exposes the full outgoing request inside both `assert_sent` predicates and [fake callbacks](#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, value)` | 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, file_name)` | Whether a multipart file was attached with the given field and filename |

For example, check multipart uploads with `has_file`:

```rust
http.assert_sent(|request| request.has_file("report", "q3.pdf"));
```

For custom assertions, `sent()` returns all recorded requests and `recorded()` returns `(Request, Response)` pairs:

```rust
let [(request, response)] = http.recorded().try_into().unwrap();

assert_eq!(response.status(), 500);
```

<a name="stray-requests"></a>
### Stray requests

Unmatched requests receive an empty `200` by default. Call `prevent_stray_requests` to fail any unexpected request with `Error::Invalid`:

```rust
use serde_json::json;

let http = client::fake()
    .with("api.github.com/*", json!({ "login": "taylorotwell" }))
    .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`:

```rust
use serde_json::json;

let http = client::fake()
    .with("api.github.com/*", json!({ "login": "taylorotwell" }))
    .allow_stray_requests(["http://127.0.0.1:5000/*"]);
```