Alexander Yurchenko

Routing and HTTP requests in Laravel Rust

Created
Updated
Author
Alexander Yurchenko

Add two routes for support tickets. The first returns a list and the second looks up a ticket by ID. In the lesson on structs and error handling, one Rust example handled both the input string and the lookup. Here the framework parses the path, and the handler checks the ID and looks up the record.

Prepare the demo project

Use the environment from the lesson on running your first application. This section uses the official v0.1.2 skeleton, laravel-rust = "=0.1.4", and Rust/Cargo 1.100.1 on Linux x86_64. Start from a copy of the skeleton before adding /hello-rust. Pin the framework version in Cargo.toml. Keep the remaining dependencies and feature flags from the skeleton. Download the exact Cargo.lock and save it as Cargo.lock in the demo project root. All three lessons use this file. Pass --locked so Cargo keeps the resolved versions.

Download the v0.1.2 skeleton archive and extract it to a new demo directory.

TOML
[package]
name = "laravel-rust-skeleton"
version = "0.1.0"
edition = "2024"
rust-version = "1.99"
publish = false

# Keep `app` as the library name when renaming the package.
[lib]
name = "app"

[dependencies]
laravel-rust = { version = "=0.1.4", features = ["database-postgres", "redis", "sqs"] }
mimalloc = "0.1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
tokio = { version = "1", features = ["fs", "io-util", "macros"] }
tracing = "0.1"

# Line tables keep panic and backtrace locations while making builds faster and binaries smaller.
[profile.dev]
debug = "line-tables-only"

[profile.dev.package."*"]
debug = false

src/main.rs starts the application configured in src/app.rs. That file already calls routing.api(routes::api::routes). Laravel adds the /api prefix to routes from src/routes/api.rs. Register /tickets in the file and request /api/tickets from the client.

This local demo uses synthetic data and has no authentication or authorization. Bind the server only to 127.0.0.1. Never expose these routes or use the published test key outside the demo.

Save the following configuration as .env in the demo project root. This application key is intentionally public and is for local testing only. Sessions and cache use memory, and the queue runs synchronously. The ticket routes never contact a database, Redis, or an external service. Port 0 asks the operating system to pick a free port on 127.0.0.1.

ENV
APP_NAME=SupportTickets
APP_ENV=local
APP_DEBUG=false
APP_KEY=base64:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
APP_URL=http://127.0.0.1
LOG_CHANNEL=stderr
LOG_LEVEL=info
CACHE_STORE=memory
QUEUE_CONNECTION=sync
SESSION_DRIVER=memory
FEATURE_STORE=memory
WORKFLOW_STORE=memory
BROADCAST_CONNECTION=discard
MAIL_MAILER=log
SMS_SENDER=log
INERTIA_SSR=false
OTEL_SDK_DISABLED=true
SERVER_HOST=127.0.0.1
SERVER_PORT=0
SERVER_MAX_CONNECTIONS=8
SERVER_SHUTDOWN_TIMEOUT=2

Define the input and response

An extractor is a framework component that obtains typed data from a request. These routes use extractors for the path and query string.

The list reads its filter from the query string. Query<TicketQuery> parses it using the struct marked #[laravel::query]. The Option<String> field gives None when status is omitted or empty. For a nonempty string, filter accepts open and closed and returns an error for other values. On the verified version, repeated scalar status parameters use the last value. Send a single filter.

On /tickets/{id}, Params<u32> extracts the path segment. A successful parse yields a number, including zero. positive_id rejects zero before the lookup, and a lookup that finds no record returns its own 404. TicketView defines the response fields. Serde serializes them and writes the Status variants in lowercase.

Replace the entire src/routes/api.rs file. The existing /version route stays in place.

RUST
use laravel::http::{Json, Query};
use laravel::routing::{Params, Router};
use laravel::{Result, abort_with};
use serde::Serialize;
use serde_json::json;

pub fn routes(route: &mut Router) {
    route.get("/version", async || Json(json!({ "laravel": laravel::VERSION })));
    route.get("/tickets", index);
    route.get("/tickets/{id}", show);
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
enum Status {
    Open,
    Closed,
}

struct Ticket {
    id: u32,
    title: String,
    status: Status,
}

#[derive(Debug, Serialize)]
// Keep the HTTP response fields separate from the stored record.
struct TicketView {
    id: u32,
    title: String,
    status: Status,
}

impl From<&Ticket> for TicketView {
    fn from(ticket: &Ticket) -> Self {
        Self {
            id: ticket.id,
            title: ticket.title.clone(),
            status: ticket.status,
        }
    }
}

fn seed_tickets() -> Vec<Ticket> {
    vec![
        Ticket {
            id: 1,
            title: "Reset password".into(),
            status: Status::Open,
        },
        Ticket {
            id: 2,
            title: "Update invoice".into(),
            status: Status::Closed,
        },
    ]
}

#[laravel::query]
struct TicketQuery {
    // Keep an unknown nonempty value available for an explicit 400.
    status: Option<String>,
}

impl TicketQuery {
    fn filter(&self) -> Result<Option<Status>> {
        match self.status.as_deref() {
            None => Ok(None),
            Some("open") => Ok(Some(Status::Open)),
            Some("closed") => Ok(Some(Status::Closed)),
            Some(_) => Err(abort_with(400, "Status must be open or closed.")),
        }
    }
}

async fn index(Query(query): Query<TicketQuery>) -> Result<Json<Vec<TicketView>>> {
    let status = query.filter()?;
    let tickets = seed_tickets();
    Ok(Json(
        tickets
            .iter()
            .filter(|ticket| status.is_none_or(|status| ticket.status == status))
            .map(TicketView::from)
            .collect(),
    ))
}

// A path parameter of the wrong type is rejected before the lookup.
async fn show(Params(id): Params<u32>) -> Result<Json<TicketView>> {
    positive_id(id)?;
    let ticket = seed_tickets()
        .into_iter()
        .find(|ticket| ticket.id == id)
        .ok_or_else(|| abort_with(404, "Ticket not found."))?;
    Ok(Json(TicketView::from(&ticket)))
}

fn positive_id(id: u32) -> Result<()> {
    if id == 0 {
        return Err(abort_with(400, "Ticket ID must be positive."));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ticket_zero_fails_the_domain_check() {
        assert!(positive_id(1).is_ok());
        assert_eq!(positive_id(0).expect_err("zero").status(), 400);
    }
}

Compare HTTP responses

Run these commands from the demo project root. After fetching dependencies, the build uses the local cache. The server reports the selected port. Use that port for requests to 127.0.0.1 and press Ctrl+C to stop the server.

BASH
cargo fetch --locked
export CARGO_TARGET_DIR="$PWD/target"
export CARGO_BUILD_BUILD_DIR="$PWD/target/build"
cargo fmt --check
cargo check --locked --offline --all-targets
cargo test --locked --offline --lib
cargo build --locked --offline
./target/debug/laravel-rust-skeleton serve --host=127.0.0.1 --port=0

The test requests send Accept: application/json. Start by selecting open tickets.

In a second terminal, enter the actual port reported by the running server. These commands connect only to 127.0.0.1.

BASH
read -r -p 'Port: ' PORT
BASE_URL="http://127.0.0.1:$PORT"

curl -i -sS --noproxy '*' -H 'Accept: application/json' "$BASE_URL/api/tickets?status=open"
curl -i -sS --noproxy '*' -H 'Accept: application/json' "$BASE_URL/api/tickets/1"
curl -i -sS --noproxy '*' -H 'Accept: application/json' "$BASE_URL/api/tickets/99"
curl -i -sS --noproxy '*' -H 'Accept: application/json' "$BASE_URL/api/tickets/abc"

The excerpts below show HTTP requests and their observed responses. The port and some headers are omitted.

HTTP
GET /api/tickets?status=open HTTP/1.1
Host: 127.0.0.1
Accept: application/json

HTTP
HTTP/1.1 200 OK
Content-Type: application/json

[{"id":1,"title":"Reset password","status":"open"}]

Both abc and 4294967296 fail when Params<u32> tries to obtain a number of the requested type. The request ends before show runs.

HTTP
GET /api/tickets/abc HTTP/1.1
Host: 127.0.0.1
Accept: application/json

HTTP
HTTP/1.1 404 Not Found
Content-Type: application/json

{"message":"Not Found"}

ID 99 parses successfully, so the request reaches the ticket lookup.

HTTP
GET /api/tickets/99 HTTP/1.1
Host: 127.0.0.1
Accept: application/json

HTTP
HTTP/1.1 404 Not Found
Content-Type: application/json

{"message":"Ticket not found."}

A zero ID gets 400 with Ticket ID must be positive.. The query ?status=pending also gets 400, with Status must be open or closed.. An unknown path gets 404 with Not Found. A DELETE /api/tickets request gets 405 with Allow: GET,HEAD.

Summary

The handler signature shows where its input comes from. Params reads a path segment, Query parses the filter, and Json serializes the ticket view. In the next lesson on validation and responses, add a POST route and follow errors from the request body to the client.

References