Rust Playbook

Course › Week 6 · Laravel Rust › Day 4 · lesson 39 of 42 · 20 min reading + 45 min practice

Errors, middleware and the HTTP client

laravel::Result and abort, a #[middleware] API key check, and the Http client with retries and fakes.

laravel::Result#[middleware]Http client

On this page
  1. 1. A configuration section
  2. 2. Middleware: the API key
  3. 3. An error with its own status
  4. 4. The HTTP client
  5. 5. When the analysis API is down
  6. The same call in PHP Laravel
  7. Practice
  8. Remember

Week 5 wrote all of this by hand: an AppError with IntoResponse, an API key check with from_fn_with_state, reqwest with a retry loop. Laravel Rust has each one built in, under the names a Laravel developer expects. This lesson puts the batch routes behind an API key, gives one of them an error with its own status, and calls the analysis API from a handler.

1. A configuration section

Settings of your own go in a section: a struct that derives Section, with each field naming the environment variable it reads. It is config/services.php with types: #[env("ANALYSIS_TIMEOUT", seconds, default = 10)] turns ANALYSIS_TIMEOUT=30 into a length of time, and required means the application will not start without the variable.

The struct derives Clone but not Debug, on purpose: a Debug derive would let {:?} print the key into a log line one day.

src/config/services.rschanged since the new application: +18
use laravel::config::Section;use laravel::time::ExactDuration; #[derive(Debug, Clone, Section)]pub struct Sentry {    #[env("SENTRY_DSN")]    pub dsn: Option<String>,} /// What the batch API needs: the key Laravel sends, and the analysis API it calls./// No Debug derive: a key must never end up in a log line.#[derive(Clone, Section)]pub struct Analysis {    /// The key every request to /api/batches must carry in X-Api-Key.    #[env("SERVICE_API_KEY", required)]    pub key: String,     /// The analysis API, such as http://127.0.0.1:8000/api/analyse.    #[env("ANALYSIS_URL", required)]    pub url: String,     /// How long one call to the analysis API may take.    #[env("ANALYSIS_TIMEOUT", seconds, default = 10)]    pub timeout: ExactDuration,}
$ laravel migrate
the environment is invalid:
  - `SERVICE_API_KEY` is required, but isn't set
  - `ANALYSIS_URL` is required, but isn't set
exit code 1

Without the two variables, nothing runs, not even migrate, and the message names both. In PHP a missing env('SERVICE_API_KEY') is null until the first request that needs it fails. Here the deploy fails, before any user is involved. The rest of this lesson runs with both set in .env.

2. Middleware: the API key

A middleware is an async function marked #[middleware]. It takes the same extractors a handler does, here the section, then the Request and Next, and either calls next.run(request) or stops. laravel::abort!(401) stops with a 401 in the application’s error format.

The key is compared with subtle’s constant-time ct_eq, as in the middleware lesson: == would stop at the first wrong byte. Laravel uses the same crate for its own token checks; here it is added to Cargo.toml.

src/http/middleware/api_key.rsnew file
use laravel::config::Section;
use laravel::http::{Next, Request, Response, middleware};
use subtle::ConstantTimeEq;

use crate::config::services::Analysis;

/// Lets a request through only with the right X-Api-Key, compared in constant time.
#[middleware]
pub async fn require_api_key(analysis: Section<Analysis>, request: Request, next: Next) -> laravel::Result<Response> {
    let sent = request.header("x-api-key").unwrap_or_default();
    if !bool::from(sent.as_bytes().ct_eq(analysis.key.as_bytes())) {
        laravel::abort!(401);
    }
    Ok(next.run(request).await)
}
Cargo.toml (part)
serde_json = "1"
subtle = "2.6.1"
thiserror = "2"

The module goes in the middleware mod.rs. It is named api_key because #[middleware] also defines a type named after the function, require_api_key, and a module of that name would clash with it:

src/http/middleware/mod.rschanged since the new application: +2
mod api_key;mod handle_inertia_requests; use laravel::http::{Next, middleware};use laravel::prelude::*; pub use api_key::require_api_key;pub use handle_inertia_requests::HandleInertiaRequests; #[middleware]pub async fn example_middleware(request: Request, next: Next) -> Response {    next.run(request).await}

route.middleware(…).group(|route| …) puts every route inside the closure behind the middleware, the Route::middleware('auth.key')->group(…) of PHP:

src/routes/api.rschanged since lesson 38: +4 −1
use laravel::prelude::*;use serde::Serialize;use serde_json::json; use crate::http::handlers::{batches, evaluations};use crate::http::middleware::require_api_key; /// What /api/status reports, for Laravel's health checks and for people.#[derive(Serialize)]
14 unchanged linesstruct Status { service: &'static str, laravel: &'static str,} pub fn routes(route: &mut Router) { route.get("/version", async || Json(json!({ "laravel": laravel::VERSION }))); route.get("/status", async || { Json(Status { service: "nordic", laravel: laravel::VERSION, }) }); route.get("/evaluations/pending", evaluations::pending);
route.get("/evaluations/{evaluation}", evaluations::show); route.get("/evaluations/{evaluation}/answers", evaluations::with_answers); route.get("/evaluations/{evaluation}/export/{format}", evaluations::export); route.post("/batches", batches::store); route.middleware(require_api_key).group(|route| { route.post("/batches", batches::store); }); route.fallback(async || laravel::abort(404));}
$ curl -si -X POST -H 'content-type: application/json' -d '{"reference": "dashboard-7f3e", "evaluation_ids": [1, 2]}' http://127.0.0.1:3000/api/batches
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 26
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 54b60ad59f402d1513697e9f8f7d5f17

{"message":"Unauthorized"}
$ curl -si -X POST -H 'x-api-key: wrong' -H 'content-type: application/json' -d '{"reference": "dashboard-7f3e", "evaluation_ids": [1, 2]}' http://127.0.0.1:3000/api/batches
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 26
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 17502b57d795c1f870a2530192c390b4

{"message":"Unauthorized"}
$ curl -si -X POST -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' -H 'content-type: application/json' -d '{"reference": "dashboard-7f3e", "evaluation_ids": [1, 2]}' http://127.0.0.1:3000/api/batches
HTTP/1.1 202 Accepted
content-type: application/json
content-length: 164
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 97f5aa21be9117b93828e0b585aede4f

{"id":1,"reference":"dashboard-7f3e","status":"queued","evaluation_ids":[1,2],"created_at":"2026-12-02T01:41:13.644328Z","updated_at":"2026-12-02T01:41:13.644328Z"}
the server’s log (stderr), after Ctrl-C
Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
POST    401  /api/batches  1.7ms
POST    401  /api/batches  8.5ms
POST    202  /api/batches  11.2ms
Stopping. Waiting up to 20s for the work in progress.

The status and version routes stay outside the group, open to anyone. Unlike axum’s route_layer in the middleware lesson, the group says which routes it covers by enclosing them, so moving a line cannot quietly change who needs a key.

3. An error with its own status

Handlers return laravel::Result, and ? turns any error into a response. Without more information that is a 500. An error type can carry its status: derive Status next to thiserror::Error, and #[status(409)] makes this variant answer 409 with its message.

retry uses it: only a failed batch may go back in the queue. update! is create!’s twin for an existing model, and it changes the model in place, which is why batch is mut.

src/http/handlers/batches.rschanged since lesson 38: +23 −2
use laravel::db::Json as JsonColumn;use laravel::model::create;use laravel::errors::Status;use laravel::model::{create, update};use laravel::prelude::*; use crate::models::AnalysisBatch;use crate::models::{AnalysisBatch, BatchStatus}; /// A batch of evaluations to analyse, as Laravel posts it.#[laravel::input]
15 unchanged lines#[validate(anyone)]pub struct NewBatch { #[validate(required, max_length(100), unique(AnalysisBatch::reference))] reference: String, #[validate(required, max_items(500), distinct, each(min_value(1)))] evaluation_ids: Vec<i64>,} /// Stores the batch as queued. The queue lesson gives it to a worker.pub async fn store(Valid(batch): Valid<NewBatch>) -> laravel::Result<(StatusCode, Json<AnalysisBatch>)> { let evaluation_ids = JsonColumn(batch.evaluation_ids); let stored = create!(AnalysisBatch { reference: batch.reference, evaluation_ids })
.await?; Ok((StatusCode::ACCEPTED, Json(stored)))} /// What can go wrong with a batch that is the caller's mistake, with the status each one answers.#[derive(Debug, thiserror::Error, Status)]pub enum BatchError { #[error("Only a failed batch can be retried.")] #[status(409)] NotFailed,} /// Puts a failed batch back in the queue.pub async fn retry(mut batch: AnalysisBatch) -> laravel::Result<Json<AnalysisBatch>> { if batch.status != BatchStatus::Failed { return Err(BatchError::NotFailed.into()); } update!(batch { status: BatchStatus::Queued }) .await?; Ok(Json(batch))}

The seeder gets a batch that failed overnight:

database/seeders/mod.rschanged since lesson 38: +11 −2
use laravel::db::seeder;use laravel::db::{Json, seeder};use laravel::model::create; use crate::models::{Answer, Evaluation, User};use crate::models::{AnalysisBatch, Answer, BatchStatus, Evaluation, User}; #[seeder(default, without_events)]pub async fn database() -> laravel::Result<()> {
25 unchanged lines create!(User::factory() { name: "Test User", email: "test@example.com", }) .await?; let stem = create!(Evaluation { school: "Alexandria STEM" }) .await?; create!(Answer { evaluation: &stem, question: "Q1", score: 5_i16, comment: "Clear explanations" }) .await?; create!(Answer { evaluation: &stem, question: "Q2", score: 4_i16 }) .await?; create!(Evaluation { school: "Cairo Language School"
}) .await?; // A batch whose analysis failed overnight, for the retry route. let evaluation_ids = Json(vec![1, 2]); create!(AnalysisBatch { reference: "nightly-2026-12-01", status: BatchStatus::Failed, evaluation_ids }) .await?; Ok(())}
src/routes/api.rschanged since the version above: +1
25 unchanged linesuse laravel::prelude::*;use serde::Serialize;use serde_json::json; use crate::http::handlers::{batches, evaluations};use crate::http::middleware::require_api_key; /// What /api/status reports, for Laravel's health checks and for people.#[derive(Serialize)]struct Status { service: &'static str, laravel: &'static str,} pub fn routes(route: &mut Router) { route.get("/version", async || Json(json!({ "laravel": laravel::VERSION }))); route.get("/status", async || { Json(Status { service: "nordic", laravel: laravel::VERSION, }) }); route.get("/evaluations/pending", evaluations::pending); route.get("/evaluations/{evaluation}", evaluations::show); route.get("/evaluations/{evaluation}/answers", evaluations::with_answers);
route.get("/evaluations/{evaluation}/export/{format}", evaluations::export); route.middleware(require_api_key).group(|route| { route.post("/batches", batches::store); route.post("/batches/{analysis_batch}/retry", batches::retry); }); route.fallback(async || laravel::abort(404));}
$ curl -si -X POST -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' http://127.0.0.1:3000/api/batches/1/retry
HTTP/1.1 200 OK
content-type: application/json
content-length: 168
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 41a692b40b7772ba80502a8546d722a8

{"id":1,"reference":"nightly-2026-12-01","status":"queued","evaluation_ids":[1,2],"created_at":"2026-12-02T01:41:34.463756Z","updated_at":"2026-12-02T01:41:34.695441Z"}
$ curl -si -X POST -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' http://127.0.0.1:3000/api/batches/1/retry
HTTP/1.1 409 Conflict
content-type: application/json
content-length: 49
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 28c8d94877407c5938dd9ca1c00752a6

{"message":"Only a failed batch can be retried."}
the server’s log (stderr), after Ctrl-C
Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
POST    200  /api/batches/1/retry  9.7ms
POST    409  /api/batches/1/retry  2.9ms
Stopping. Waiting up to 20s for the work in progress.

The second retry finds the batch queued, so it is a 409 with the error’s message. An error with a 4xx status is an expected outcome: it is shown to the client and not logged as a failure. A 5xx is the other way round, as the last section shows.

4. The HTTP client

laravel::http::client is the Http facade. client::post(url).json(…) builds the request, timeout limits one attempt, and retry(3, Backoff::exponential(200.milliseconds())) makes up to three attempts, 200 ms then 400 ms apart. With retry, a 4xx or 5xx answer counts as a failure too, so the response that reaches .json() was a success.

with_context adds a sentence for the log to whatever error comes back, the way report() with context does in PHP. .json() decodes the body into Sentiment, and a body of the wrong shape is an error, not a half-filled object.

src/http/handlers/evaluations.rschanged since lesson 38: +29 −1
use laravel::config::Section;use laravel::http::client::{self, Backoff};use laravel::prelude::*;use serde::{Deserialize, Serialize}; use serde_json::json; use crate::config::services::Analysis;use crate::models::{Evaluation, Status}; /// The formats an evaluation can be exported in. Any other value in the URI is a 404.
43 unchanged lines#[derive(Clone, Copy, Deserialize, Serialize)]#[serde(rename_all = "lowercase")]pub enum Format { Csv, Xlsx,} #[derive(Serialize)]pub struct Export { evaluation: i64, format: Format, url: String,} pub async fn export(Params((id, format)): Params<(i64, Format)>) -> Json<Export> { let extension = match format { Format::Csv => "csv", Format::Xlsx => "xlsx", }; Json(Export { evaluation: id, format, url: format!("/exports/evaluation-{id}.{extension}"), })} /// One evaluation, found by the {evaluation} in the URI. An unknown id is a 404 before this runs.pub async fn show(evaluation: Evaluation) -> Json<Evaluation> { Json(evaluation)} /// Every evaluation still waiting for the analysis, oldest first.pub async fn pending() -> laravel::Result<Json<Vec<Evaluation>>> { let evaluations = Evaluation::query() .filter(Evaluation::status.eq(Status::Pending)) .order_by(Evaluation::id) .get() .await?; Ok(Json(evaluations))} /// One evaluation with its answers, in two queries whatever the number of answers.pub async fn with_answers(Params(id): Params<i64>) -> laravel::Result<Json<Evaluation>> {
let evaluation = Evaluation::query().with(Evaluation::answers).find_or_fail(id).await?; Ok(Json(evaluation))} /// What the analysis API answers for one evaluation.#[derive(Deserialize, Serialize)]pub struct Sentiment { evaluation_id: i64, positive: i32, negative: i32, neutral: i32,} /// Sends an evaluation's comments to the analysis API and answers with its result.pub async fn analyse(analysis: Section<Analysis>, Params(id): Params<i64>) -> laravel::Result<Json<Sentiment>> { let evaluation = Evaluation::query().with(Evaluation::answers).find_or_fail(id).await?; let comments: Vec<&str> = evaluation.answers.iter().filter_map(|a| a.comment.as_deref()).collect(); let sentiment: Sentiment = client::post(&analysis.url) .json(json!({ "evaluation_id": evaluation.id, "comments": comments })) .timeout(analysis.timeout) .retry(3, Backoff::exponential(200.milliseconds())) .await .with_context(|| format!("evaluation {id} could not be analysed"))? .json()?; Ok(Json(sentiment))}
src/routes/api.rschanged since the version above: +1
26 unchanged linesuse laravel::prelude::*;use serde::Serialize;use serde_json::json; use crate::http::handlers::{batches, evaluations};use crate::http::middleware::require_api_key; /// What /api/status reports, for Laravel's health checks and for people.#[derive(Serialize)]struct Status { service: &'static str, laravel: &'static str,} pub fn routes(route: &mut Router) { route.get("/version", async || Json(json!({ "laravel": laravel::VERSION }))); route.get("/status", async || { Json(Status { service: "nordic", laravel: laravel::VERSION, }) }); route.get("/evaluations/pending", evaluations::pending); route.get("/evaluations/{evaluation}", evaluations::show); route.get("/evaluations/{evaluation}/answers", evaluations::with_answers); route.get("/evaluations/{evaluation}/export/{format}", evaluations::export);
route.middleware(require_api_key).group(|route| { route.post("/batches", batches::store); route.post("/batches/{analysis_batch}/retry", batches::retry); route.post("/evaluations/{evaluation}/analyse", evaluations::analyse); }); route.fallback(async || laravel::abort(404));}
$ curl -si -X POST -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' http://127.0.0.1:3000/api/evaluations/1/analyse
HTTP/1.1 200 OK
content-type: application/json
content-length: 57
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 33f8a116ed029b34989341efdf648303

{"evaluation_id":1,"positive":1,"negative":0,"neutral":0}
the server’s log (stderr), after Ctrl-C
Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
POST    200  /api/evaluations/1/analyse  124.9ms
Stopping. Waiting up to 20s for the work in progress.

A little over 100 ms in the log: the analysis API takes 100 ms per evaluation. Retrying a POST is safe here because analysing the same comments twice gives the same answer; the docs warn that a retry resends the request, so a call that is not idempotent needs an idempotency key, the role the batch reference plays.

5. When the analysis API is down

The same application with ANALYSIS_URL pointing at a port where nothing listens, and APP_DEBUG=false, as in production:

$ curl -si -X POST -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' http://127.0.0.1:3000/api/evaluations/1/analyse
HTTP/1.1 500 Internal Server Error
content-type: application/json
content-length: 26
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: fa5af2f91c2588d16d24491eddd5e7f6

{"message":"Server Error"}
the server’s log (stderr), after Ctrl-C
Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
2026-12-02T01:41:57.861722Z ERROR request{id=fa5af2f91c2588d16d24491eddd5e7f6 method=POST path=/api/evaluations/1/analyse route="/api/evaluations/{evaluation}/analyse"}: laravel::errors: evaluation 1 could not be analysed: the HTTP request to http://127.0.0.1:8999/api/analyse failed: Connection refused (os error 111) type="laravel::http::client::error::Error" location=src/http/handlers/evaluations.rs:77:10 causes=["the HTTP request to http://127.0.0.1:8999/api/analyse failed: Connection refused (os error 111)","error sending request","client error (Connect)","tcp connect error","Connection refused (os error 111)"]
POST    500  /api/evaluations/1/analyse  625.3ms
Stopping. Waiting up to 20s for the work in progress.

The client gets {"message":"Server Error"} and nothing else. The log has the whole story on one line: the context (evaluation 1 could not be analysed), the URL, the chain of causes down to Connection refused, the request id the client saw in x-request-id, and the file and line. Over half a second passed before the answer: three attempts, with 200 ms and 400 ms of backoff between them.

With APP_DEBUG=true, the default in a local .env, the JSON answer would include the error’s type, file and line. That is the debug page of PHP Laravel, and it must be off in production for the same reason.

The same call in PHP Laravel

app/Http/Controllers/AnalyseEvaluationController.php
<?php

namespace App\Http\Controllers;

use App\Models\Evaluation;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;

class AnalyseEvaluationController
{
    public function __invoke(Evaluation $evaluation): JsonResponse
    {
        $comments = $evaluation->answers->pluck('comment')->filter()->values();

        $sentiment = Http::timeout(config('services.analysis.timeout'))
            ->retry(3, fn (int $attempt): int => 100 * 2 ** $attempt)
            ->post(config('services.analysis.url'), [
                'evaluation_id' => $evaluation->id,
                'comments' => $comments,
            ])
            ->throw()
            ->json();

        return response()->json($sentiment);
    }
}

Line for line the same call. Two differences show only when something is off: $evaluation->answers here is a lazy query that runs inside the controller without being asked for, and ->json() returns whatever array came back. In Rust the answers were loaded with with, and the body either fits Sentiment or the request fails with an error that says so.

PracticeThe errors, middleware and HTTP client guides

Read errors up to “Error pages”, the first half of middleware, and the HTTP client up to “Concurrent requests”.

Exercise: a 503 with Retry-After

When the analysis API is unreachable, answer 503 with Retry-After: 30 instead of 500: match the client’s error (client::Error::Connection(_)) and return laravel::abort(503).with_header("retry-after", "30"). Laravel’s Http::retry on the PHP side then knows to wait, as with the Week 5 service.

Remember

  • Settings are a Section with #[env(…, required)]: the application will not start without them.
  • An error type can carry its status (#[derive(Status)]); a 5xx shows the client Server Error and logs the cause with its context.

Tomorrow: queues. A job that analyses a batch in the background with retries, and laravel::task to run its calls at the same time.