# 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は、外部APIやWebサービスへのリクエストに使える [reqwest](https://docs.rs/reqwest) ベースの表現力豊かなHTTPクライアントを提供します。適切なタイムアウト、設定可能な再試行、充実したエラー処理を備え、テストではレスポンスをfakeにしてネットワークへアクセスせずに検証できます。


クライアントのすべての関数と型は `laravel::http::client` モジュールにあります。

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

## Making requests


`get`、`post`、`put`、`patch`、`delete`、`head` でリクエストを開始し、オプションをチェーンしてawaitしてください。

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

let response = client::get("https://example.com/users").await?;
```


awaitすると送信し、レスポンス本文全体を読み取ります。`404` や `500` も `Ok(response)` を返し、`?` が失敗するのは送信不能やタイムアウトの場合だけです。2xx以外を自動でエラーにする方法は [error handling](#error-handling) を参照してください。


ハンドラー、コンソールコマンド、キュージョブ、リスナーから送信できます。自分で生成するタスクでは、アプリケーションのHTTPクライアントコンテキストを継承できるよう、`tokio::spawn` の代わりに [`laravel::task::spawn`](/ja/rust/docs/tasks#spawned-tasks) を使ってください。

<a name="responses"></a>

### Responses


`Response` はサーバーの応答を確認する次のメソッドを提供します。

| メソッド | 戻り値 |
| --- | --- |
| `status()` | 整数と直接比較できる `StatusCode`（`response.status() == 404`）。 |
| `successful()` | 2xxなら `true`。 |
| `redirect()` | 3xxなら `true`。 |
| `failed()` | 4xxまたは5xxなら `true`。 |
| `client_error()`, `server_error()` | それぞれ4xx、5xxなら `true`。 |
| `header("x-name")` | `Option<&str>` のヘッダー値。 |
| `headers()` | すべてのレスポンスヘッダーを `&HeaderMap` で返す。 |
| `url()` | リダイレクト後の最終URL。 |
| `bytes()`、`text()` | `&Bytes` または `&str` のレスポンス本文。 |
| `json::<T>()` | JSONからデシリアライズした本文を `Result<T, Error>` で返す。 |


リクエスト完了時には本文がバッファリング済みのため、`json()` と `text()` は同期メソッドです。独自の構造体へ、または少数のフィールドだけが必要なら `serde_json::Value` へデコードしてください。

```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


任意の `Serialize` 値をJSON本文で送るには `json` を使います。

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

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


キーと値のペア、`json!` オブジェクト、`Serialize` 構造体からクエリパラメータを追加するには `query` を使います（`None` フィールドは自動で省略されます）。

```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?;
```


Rustの配列は要素が同じ型である必要があります。型が混在する場合は `json!` や `Serialize` 構造体を使うか、複数の `.query(..)` をチェーンしてください。


URLエンコード形式には `form`、明示したコンテンツ型の生の本文には `body`、ディスクから直接ストリーミングするには `body_file` を使います。

```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


マルチパートアップロードには、`attach` にフォームのフィールド名と `Attachment` を渡します。`form` のフィールドもファイルと一緒に含まれます。

```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` はディスクからストリーミングし、相対パスをアプリケーションのベースパス基準で解決します。`Attachment::from_data(bytes, "avatar.png")` はメモリ内のバイトを指定名で送信します。`named` と `mime` で名前やMIMEタイプを上書きしなければ、ファイル名からコンテンツ型を推定します。

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


受信した `UploadedFile` をハンドラーから直接転送することもできます。

```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())
}
```


Laravelはリクエスト完了後に一時アップロードを削除するため（[cleans up temporary uploads](/ja/rust/docs/requests#keeping-uploaded-files)）、キュージョブやバックグラウンドタスクではなく、ハンドラー内で転送してください。

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

### Headers


単一ヘッダーは `header`、複数なら `headers` で追加します。同じ名前の既存ヘッダーは置き換わります。

```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?;
```


`accept` または短縮形の `accept_json` で `Accept` ヘッダーを設定します。

```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


送信するリクエストにはBearerトークンやHTTP基本認証を使えます。`Authorization` ヘッダー（`Authorization: Bearer <token>`）へトークンを付けるには `token` を使います。

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

let response = client::get("https://api.github.com/user")
    .token("your-token")
    .await?;
```


`basic_auth` でHTTP基本認証の認証情報を指定できます。ユーザー名とパスワードをBase64でエンコードし、`Authorization: Basic` ヘッダーに設定します。

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

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


独自の認証方式やAPIキーヘッダーが必要なAPIには、`header` で直接渡してください。

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

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


本番ではAPIキーやトークンをソースに含めず、[custom config section](/ja/rust/docs/configuration#your-own-config-sections) に保存し、その設定をハンドラーやサービスに注入してください。

```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は `Authorization`、`Proxy-Authorization`、`Cookie` の値を機密情報に指定し、デバッグ出力で伏せ字にします。

<a name="base-urls-and-reusable-requests"></a>

### Base URLs and reusable requests


複数箇所から同じAPIを呼ぶ場合は、`client::base_url` で再利用可能な `PendingRequest` テンプレートを作ります。共通ヘッダー、トークン、エラー処理を一度設定し、相対パスで `get`、`post` などを呼び出してください。

```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


`../admin` などが対象パスを変えるため、`format!` でユーザー入力をURLへ埋め込まないでください。`{name}` と `url_parameters` を使うと、各パラメータが単一パスセグメントとしてパーセントエンコードされます。

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

client::get("https://api.github.com/repos/{owner}/{repo}")
    .url_parameters([("owner", "laravel"), ("repo", "framework")])
    .await?;
```


`url_parameters` は `query` と同様、ペアや `Serialize` 構造体を受け取ります。ベースURL全体などをセグメントエンコードせず展開するには `{+name}` を使います。

<a name="timeouts"></a>

### Timeouts


デフォルトでは全レスポンスを最大30秒、接続確立を最大10秒待ちます。個別の制限は `timeout` で変更できます。

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

client::get("https://example.com").timeout(3.seconds()).await?;
```


タイムアウトすると、`error.is_timeout()` が `true` の `Error::Connection` を返します。全体の既定値変更は [configure the client](#configuring-the-client) を参照してください。

<a name="retries"></a>

### Retries


接続エラーや2xx以外のエラーを自動再試行するには `retry` を使います。最大試行回数と、固定遅延または `Backoff::exponential` による待ち時間を渡します。

```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?;
```


全試行が失敗すると、最後のエラーを返します。


`429` や `503` に `Retry-After`（秒またはHTTP日時）が含まれる場合、[timeout](#timeouts) または `total_timeout` に収まる限り、少なくともその時間を待ちます。残り時間を超える場合は直ちに再試行をやめ、処理や再キュー登録のためにエラーを返します。


各試行に独自の [timeout](#timeouts) があるため、複数回の再試行でハンドラーの許容遅延を超える場合があります。全試行とバックオフの合計には `total_timeout` を使ってください。

```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?;
```


`total_timeout(5.seconds())` では、個別試行が2秒でも残り3秒なら3秒の `Retry-After` を尊重します。24時間の `Retry-After` は即座に失敗します。


特定のエラーだけを再試行するには、`retry_when` に条件関数を渡します（試行番号は1始まりです）。

```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]
> 再試行では同じHTTPリクエストを再送します。冪等な操作か冪等性キーで保護されたリクエストだけを再試行してください。

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

### Error handling


通常4xx、5xxも `Ok(response)` を返します。`ensure_successful` を呼ぶと2xx以外を `Error::Status` に変換します。

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

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


応答を調べてから `response.ensure_successful()?` を呼ぶこともできます。


`client::Error` は失敗を4種類に分類します。

| バリアント | 原因 |
| --- | --- |
| `Error::Connection` | 応答なし（ホスト到達不能、TLS失敗、タイムアウト）。 |
| `Error::Status` | `ensure_successful` または `retry` で2xx以外。`error.response()` で確認。 |
| `Error::Decode` | `json()` が対象型へ変換できない。 |
| `Error::Invalid` | リクエスト構築不能（不正なURLやヘッダー）。 |


個別の失敗を処理するには `client::Error` をパターンマッチしてください。

```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()),
}
```


`?` で `laravel::Error` に変換して返すと、Laravelは失敗を報告し（[reports](/ja/rust/docs/errors)）、`500` を返してURLと本文冒頭を記録します。

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

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

## Concurrent requests


独立した複数の応答が必要なら、`.send()` で各futureを取得し、[`task::try_join!`](/ja/rust/docs/tasks#concurrent-operations) で並行送信します。

```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(),
)?;
```


多数のリクエストの並行数を制限するには、入力順を保つ `.buffered(limit)` のストリームで包んでください。

```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


大きなダウンロードやAIチャット補完などでは、全本文をメモリへ読み込む代わりに `stream()` を呼びます。`stream()` はヘッダー到着時に `StreamedResponse` を返します。


`chunks()` で本文をバイトのチャンク単位に反復できます。

```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...
}
```


メモリに保持せず、`chunks()` を [file storage](/ja/rust/docs/filesystem#streaming-large-files) へ直接渡せます。

```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` は `Response` と同じ `status()`、`header()`、状態ヘルパーを提供します。本文は一度だけ消費でき、生バイトなら `chunks()`、[server-sent events](#server-sent-events) なら `events()`、残りを通常の `Response` にバッファリングするなら `into_response()` を使います。


ストリーミング中の [timeout](#timeouts) は全体ではなく各チャンク読み取りに適用されるため、活動中の長時間ストリームはタイムアウトしません。

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

### Server-sent events


多くのAI、リアルタイムAPIは [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) で配信します。`events()` は完了したイベントを順に生成し、`data()` と `json()` を提供します。


次の例はOpenAIのストリーミング補完を [`EventStream`](/ja/rust/docs/responses#event-streams) としてブラウザーへ中継します。

```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


`laravel::http::client` の全トップレベルヘルパー（`client::get`、`client::post`、`client::base_url` など）は、アプリケーション管理の共有 `Client` を使います。1つの `Client` を共有することで、プールされたTCP/TLS接続、既定タイムアウト、リクエストフックを再利用できます。


共有クライアントは次の既定値を使います。

| 設定 | デフォルト |
| --- | --- |
| `timeout` | 30秒 |
| `connect_timeout` | 10秒 |
| `user_agent` | `Laravel-Rust/<version>` |


全体の既定値を変更するには `Client` を作り、`src/app.rs` の `.with_services` 内で `app.instance` に登録します。

```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");
                }),
        );
    })
```


遅延生成する `singleton` ではなく `app.instance` に登録すると、起動中に他サービスがHTTPを送る時点で利用可能になります。


ライフサイクルフックは、クライアントを通る全リクエストとレスポンスを検査、変換できます。`before_sending` は送信前に登録順で実行され、`after_response` は再試行やテストのfakeを含む全レスポンスを観察します。


`before_sending` を特定APIにだけ適用するには、変更前に `request.url()` を確認してください。

```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


独自CA証明書、相互TLS、HTTPプロキシ、リダイレクト方針など、基盤の `reqwest` を直接設定するには `configure_transport` へクロージャを渡します。reqwestの `ClientBuilder` を受け、設定済みビルダーを返します。


同梱のreqwestと常にバージョンを合わせるため、型は `laravel::http::client::reqwest` からインポートしてください。

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

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


共有 `Client` ではなく個別リクエストでも `configure_transport` を呼べます。そのリクエスト専用の接続プールを作り、他には影響しません。

<a name="dedicated-clients"></a>

### Dedicated clients


特定の外部連携だけに独自の `User-Agent`、厳しいタイムアウト、TLS証明書、別のリダイレクト方針が必要な場合、専用 `Client` を作り、`get`、`post`、`base_url` などを直接呼べます。


各 `Client` は独自の接続プールを持つため、毎回ハンドラーで作らないでください。専用 `Client` を [service](/ja/rust/docs/container) で包み、`src/app.rs` に一度登録して必要な場所に注入します。

```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())
    }
}
```


`src/app.rs` に登録し、ハンドラーで `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
}
```


専用 `Client` でも、[tests](#testing) では `client::fake()` が自動で捕捉します。

<a name="logging"></a>

## Logging


HTTPクライアントは送信ごとに `laravel::http::client` ターゲットへ `debug` ログを出し、メソッド、URL、状態、`duration_ms` または失敗理由を記録します。`LOG_LEVEL=info,laravel::http::client=debug` で有効化します。ログURLやエラーから認証情報とクエリ文字列を自動除去し、APIキー漏洩を防ぎます。


[distributed tracing](/ja/rust/docs/tracing#traces-across-services) が有効なら、各試行が独自のspanとW3C `traceparent` ヘッダーを作るため、再試行では試行ごとのspanが表示されます。

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

## Testing

<a name="faking-responses"></a>

### Faking responses


テストで `client::fake()` を呼ぶと、ネットワークを使わず捕捉してfake応答を返します。デフォルトではすべて空の `200` です。

```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);
}
```


検証中は返されたfakeハンドルを保持してください。破棄すると実ネットワークに戻ります。各fakeはアプリケーション単位に分離され、同時テストで干渉しません。


カスタム応答には `.with(..)` へURLパターンを渡します。URL内の任意の箇所に一致し、`*` をサポートして登録順に照合します。状態コード、文字列、JSON、`client::response()` ビルダーを返せます。

```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");
```


`Error::Connection` を返す `client::failed_connection()` で通信失敗を模擬できます。

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


fakeでもフックと再試行ロジックは実行されますが、試行間では待機しません。

> [!NOTE]
> `client::fake()` は `laravel::http::client` 経由を捕捉します。独自HTTPクライアントを作る外部SDKは対象外です。

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

### Response sequences


同じURLに順番に異なる応答を返す `client::sequence()` は再試行テストに便利です。

```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" })),
);
```


シーケンスを使い切ると、`when_empty` にフォールバックがなければ `Error::Invalid` になります。`push` と同じく `when_empty` は状態コード、文字列、JSON、`client::response()`、`client::failed_connection()`、[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


受け取ったリクエストに依存するfakeには、`with` にクロージャを渡します。`&Request` を受け、状態コード、文字列、JSON、`client::response()` などを返せます。

```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
    }
});
```


コールバック内でも、アサーションと同じ [`Request` methods](#inspecting-requests) で送信内容の任意の部分を調べられます。

<a name="faking-streamed-responses"></a>

### Faking streamed responses


`stream()` が呼ばれるとfake本文は行ごとに届きます。次の例は [chat handler](#server-sent-events) 用のOpenAI 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


fakeは有効な間、再試行を含む全送信を記録します。`assert_sent` で少なくとも1件が条件に合うことを確認できます。

```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` は `assert_sent` の条件関数と [fake callbacks](#fake-callbacks) の両方で、送信全体を公開します。

| メソッド | 説明 |
| --- | --- |
| `method()` | HTTPの `Method`（`GET`、`POST` など） |
| `url()` | ベースURLとクエリ文字列を含む解決済みURL |
| `header(name)` | `Option<&str>` のヘッダー文字列 |
| `has_header(name, value)` | 指定値で送信したか |
| `headers()` | 全送信ヘッダーの `HeaderMap` |
| `body()` | 生の本文バイト（`&[u8]`） |
| `data()` | JSON、フォーム、マルチパート文字列を解析した `serde_json::Value` |
| `json::<T>()` | JSON本文を型付き構造体へ変換 |
| `files()` | 添付マルチパートファイル（`&[SentFile]`） |
| `has_file(name, file_name)` | 指定フィールド、ファイル名で添付したか |


たとえば `has_file` でマルチパートのアップロードを確認します。

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


独自アサーションには、全記録を返す `sent()` や `(Request, Response)` ペアを返す `recorded()` を使えます。

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

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

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

### Stray requests


一致しないリクエストは通常空の `200` を受け取ります。`prevent_stray_requests` を呼ぶと、予期しない要求を `Error::Invalid` にします。

```rust
use serde_json::json;

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


他の予期しない要求を遮断したままローカルテストサーバーなど特定の実ホストだけを許可するには、`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/*"]);
```