Rust Playbook

Course › Week 6 · Laravel Rust › Day 2 · lesson 37 of 42 · 15 min reading + 45 min practice

Routes, handlers and typed input

Route files, parameters and route model binding, and validation declared on a struct.

RouterParams#[laravel::input]Valid

On this page
  1. 1. A handler module
  2. 2. Input with its rules
  3. 3. Who may submit it
  4. The same route in PHP Laravel
  5. Practice
  6. Remember

In PHP Laravel a route points at a controller method, and a Form Request validates the input before the method runs. Laravel Rust has both, with one change of habit: the rules live on the struct the input is read into, so a handler that receives the input can only receive valid input.

This lesson adds two API routes to the nordic application from the previous lesson: one with route parameters, and the POST /api/batches of the Week 5 service, validated the Laravel Rust way. Storing the batch needs a model, the subject of the models lesson.

1. A handler module

Handlers are async functions in src/http/handlers, one module per resource, the way controllers are one class per resource. A handler’s arguments are extractors, as in axum: here Params, which parses the route’s parameters into the type you give it. Two parameters arrive as a tuple, in the order the URI names them.

The type is the constraint. i64 accepts only whole numbers, and Format accepts only csv and xlsx: #[serde(rename_all = "lowercase")] from the serde lesson maps the variants to those words.

src/http/handlers/evaluations.rsnew file
use laravel::prelude::*;
use serde::{Deserialize, Serialize};

/// The formats an evaluation can be exported in. Any other value in the URI is a 404.
#[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}"),
    })
}

A module exists once a mod line names it, as in the modules lesson. The handlers’ mod.rs gets one:

src/http/handlers/mod.rschanged since the new application: +1
pub mod evaluations;pub mod welcome;

And the route file points a route at the handler by its path, evaluations::export, as routes/api.php points at [EvaluationController::class, 'export']:

src/routes/api.rschanged since lesson 36: +3
use laravel::prelude::*;use serde::Serialize;use serde_json::json; use crate::http::handlers::evaluations; /// What /api/status reports, for Laravel's health checks and for people.#[derive(Serialize)]struct Status {
9 unchanged lines 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/{evaluation}/export/{format}", evaluations::export); route.fallback(async || laravel::abort(404));}
$ curl -si http://127.0.0.1:3000/api/evaluations/1042/export/csv
HTTP/1.1 200 OK
content-type: application/json
content-length: 71
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: 021665d7b763016745655314bb0c900c

{"evaluation":1042,"format":"csv","url":"/exports/evaluation-1042.csv"}
$ curl -si http://127.0.0.1:3000/api/evaluations/1042/export/pdf
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 23
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: d6df647d02f79ead3a921e1c7d6cf0e8

{"message":"Not Found"}
$ curl -si http://127.0.0.1:3000/api/evaluations/abc/export/csv
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 23
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: e68daf50894245b61fc0e449be6e6b76

{"message":"Not Found"}
the server’s log (stderr), after Ctrl-C
Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
GET     200  /api/evaluations/1042/export/csv  1.2ms
GET     404  /api/evaluations/1042/export/pdf  1.7ms
GET     404  /api/evaluations/abc/export/csv  0.9ms
Stopping. Waiting up to 20s for the work in progress.

pdf is not a Format and abc is not an i64, so both are a 404, and the handler never ran. That is a difference from plain axum, which answered a parameter that did not parse with 400 in the routing lesson. Laravel’s reading is that /evaluations/abc names no evaluation, so the page is not found.

If a handler takes an argument the framework cannot build, or puts them in the wrong order, the route line fails to compile with “this function can’t handle requests”. Adding #[laravel::routing::debug_handler] above the handler makes the compiler name the argument at fault.

2. Input with its rules

#[laravel::input] marks a struct as request input: it derives Deserialize and Validate for it. Each field carries its rules in #[validate(…)], in the order they run, like the rules() array of a Form Request, with the names you know: required, max_length, max_items, distinct, and each(…) for the rules of every item of a list.

The field’s type is a rule too. A String field accepts only text and a Vec<i64> only a list of whole numbers, so there is no string or array rule to write.

Valid<T> is the extractor that reads the body into T and checks every rule. The handler runs only when the input passed; it receives a NewBatch, never an unchecked one. As in Week 5 the body-reading extractor must be the last argument.

src/http/handlers/batches.rsnew file
use laravel::prelude::*;
use serde::Serialize;

/// A batch of evaluations to analyse, as Laravel posts it.
#[laravel::input]
#[validate(anyone)]
pub struct NewBatch {
    #[validate(required, max_length(100))]
    reference: String,
    #[validate(required, max_items(500), distinct, each(min_value(1)))]
    evaluation_ids: Vec<i64>,
}

#[derive(Serialize)]
pub struct Accepted {
    reference: String,
    evaluations: usize,
}

pub async fn store(Valid(batch): Valid<NewBatch>) -> (StatusCode, Json<Accepted>) {
    let accepted = Accepted {
        evaluations: batch.evaluation_ids.len(),
        reference: batch.reference,
    };
    (StatusCode::ACCEPTED, Json(accepted))
}

The module and the route, as in section 1:

src/http/handlers/mod.rschanged since the version above: +1
pub mod batches;pub mod evaluations;pub mod welcome;
src/routes/api.rschanged since the version above: +2 −1
use laravel::prelude::*;use serde::Serialize;use serde_json::json; use crate::http::handlers::evaluations;use crate::http::handlers::{batches, evaluations}; /// What /api/status reports, for Laravel's health checks and for people.#[derive(Serialize)]
11 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/{evaluation}/export/{format}", evaluations::export); route.post("/batches", batches::store); route.fallback(async || laravel::abort(404));}
$ curl -si -H 'content-type: application/json' -d '{"reference": "dashboard-7f3e", "evaluation_ids": [1042, 1043]}' http://127.0.0.1:3000/api/batches
HTTP/1.1 202 Accepted
content-type: application/json
content-length: 46
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: d0b6f0f105e0f94b39af09daa84caec9

{"reference":"dashboard-7f3e","evaluations":2}
$ curl -si -H 'content-type: application/json' -d '{"reference": "", "evaluation_ids": [1042, 1042, 0]}' http://127.0.0.1:3000/api/batches
HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 265
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: b55e37398c0f65a4486e5ae5b54c358f

{"message":"The reference field is required. (and 2 more errors)","errors":{"reference":["The reference field is required."],"evaluation_ids":["The evaluation ids field has a duplicate value."],"evaluation_ids.2":["The evaluation_ids.2 field must be at least 1."]}}
$ curl -si -H 'content-type: application/json' -d '{"reference": "dashboard-7f3e", "evaluation_ids": "1042"}' http://127.0.0.1:3000/api/batches
HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 131
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: eac83833a765915493021bc1638a77b8

{"message":"The evaluation ids field must be an array.","errors":{"evaluation_ids":["The evaluation ids field must be an array."]}}
$ curl -si -H 'content-type: application/json' -d '{"reference": ' http://127.0.0.1:3000/api/batches
HTTP/1.1 400 Bad Request
content-type: application/json
content-length: 78
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: 4a619bd1de6125ff4d732937d229417f

{"message":"Invalid JSON body: EOF while parsing a value at line 1 column 14"}
the server’s log (stderr), after Ctrl-C
Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
POST    202  /api/batches  1.8ms
POST    422  /api/batches  2.6ms
POST    422  /api/batches  2.3ms
POST    400  /api/batches  1.0ms
Stopping. Waiting up to 20s for the work in progress.

The 422 is the body a PHP Laravel API sends: message with the first error and a count of the rest, and errors with every field’s messages, items of a list in dot notation (evaluation_ids.2). In Week 5 that took a hand-written function; here it is the default. Laravel’s Http client and $response->json('errors') read it unchanged.

A body that is not JSON at all is a 400 with the parser’s message, and a field of the wrong type ("1042" for the list) is a 422 saying so. The same struct also reads a form post (reference=x&evaluation_ids[]=5): a route in web.rs would redirect back with the errors in the session instead, as a PHP form does.

3. Who may submit it

#[validate(anyone)] on the struct says who may submit this input: anyone who can reach the route. It is the authorize() method of a Form Request, and it is not optional. Remove the line and the application no longer compiles: the error reads “NewBatch doesn’t say who may submit it”, and its note lists the choices.

The choices are anyone, authenticated (any logged-in user), a policy with authorize(Policy::method), or your own authorize function. A PHP Form Request without an authorize() method lets every request through without a word; here the decision is forced at compile time, before the route can exist.

anyone is right for this route only because the batch routes will sit behind an API key check, the middleware lesson’s subject. A route that anyone on the internet can reach gets authenticated or a policy.

The same route in PHP Laravel

app/Http/Requests/StoreBatchRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreBatchRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    /** @return array<string, list<string>> */
    public function rules(): array
    {
        return [
            'reference' => ['required', 'string', 'max:100'],
            'evaluation_ids' => ['required', 'array', 'max:500', 'distinct'],
            'evaluation_ids.*' => ['integer', 'min:1'],
        ];
    }
}

The rules match one for one. The difference is what the controller receives: $request->validated()['evaluation_ids'] is still mixed to PHPStan, while batch.evaluation_ids is a Vec<i64> the compiler knows. And a forgotten authorize() in PHP means “everyone”; in Laravel Rust, input without an answer to “who may submit this” does not compile.

PracticeThe routing, handlers and validation guides

Read routing (parameters and groups), handlers and the first half of validation, up to “Displaying errors”. The same files are in the crate’s docs/ folder.

Exercise: an optional channel

Add channel: Option<Channel> to NewBatch, where Channel is an enum of email and sms with #[derive(Clone, Copy, Debug, Serialize, Deserialize, Enum)]. Check that a missing channel passes, "sms" passes, and "fax" is a 422 naming the field.

Remember

  • Rules live on the input struct (#[laravel::input] + #[validate]); a handler that takes Valid<T> only ever sees valid input.
  • A route parameter’s type is its constraint: a value that does not parse is a 404.

Tomorrow: models and migrations. A #[model] for the Week 4 evaluations table, queries the compiler checks, and the batch stored for real.