CRUD in Laravel Rust: a support ticket API
Continue the project from the lesson on PostgreSQL and migrations. The table and earlier queries already work. Add two routes for a single ticket, using the same Cargo.lock for the data lessons, connection configuration, and migrations.
Define the update rules
Creation keeps its existing input behavior: it reads only title and ignores extra keys. PATCH accepts an object with title, status, or both. An omitted field retains its value. Explicit null, an empty object, an unknown field, or a server-owned field returns 422. Titles are trimmed and checked against the existing length rule, and status values must be open or closed.
Replace src/routes/api.rs. To enforce a strict field list for PATCH, use the native Json<Value> extractor for syntax and content type, then decode the object with Serde into PatchTicket. The deny_unknown_fields rule applies in the second step. The decoder for a supplied field accepts a string and rejects null. Only an omitted key becomes None.
mod store;
use store::{Ticket, database_error};
use laravel::container::Inject;
use laravel::db::DatabaseManager;
use laravel::http::middleware::LimitBody;
use laravel::http::{Created, Json, NoContent, Query};
use laravel::routing::{Params, Router};
use laravel::validation::{InvalidInput, Validate};
use laravel::{Result, abort_with};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Value, 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);
route
.patch("/tickets/{id}", update)
.middleware(LimitBody::bytes(TICKET_BODY_LIMIT));
route.delete("/tickets/{id}", delete);
route
.post("/tickets", create)
.middleware(LimitBody::bytes(TICKET_BODY_LIMIT));
route
.post("/tickets/preview", preview)
.middleware(LimitBody::bytes(TICKET_BODY_LIMIT));
}
#[laravel::query]
struct TicketQuery {
// Keep an unknown nonempty value available for an explicit 400.
status: Option<String>,
}
impl TicketQuery {
fn filter(&self) -> Result<Option<&str>> {
match self.status.as_deref() {
None => Ok(None),
Some(status @ ("open" | "closed")) => Ok(Some(status)),
Some(_) => Err(abort_with(400, "Status must be open or closed.")),
}
}
}
async fn index(db: Inject<DatabaseManager>, Query(query): Query<TicketQuery>) -> Result<Json<Vec<Ticket>>> {
let status = query.filter()?;
let db = db.default_connection().map_err(database_error)?;
Ok(Json(Ticket::list(&db, status).await.map_err(database_error)?))
}
async fn show(db: Inject<DatabaseManager>, Params(id): Params<u32>) -> Result<Json<Ticket>> {
positive_id(id)?;
let db = db.default_connection().map_err(database_error)?;
// Handle the query error before checking for a missing row, so a database failure cannot become a 404.
let ticket = Ticket::get(&db, i64::from(id))
.await
.map_err(database_error)?
.ok_or_else(|| abort_with(404, "Ticket not found."))?;
Ok(Json(ticket))
}
async fn create(db: Inject<DatabaseManager>, Json(input): Json<CreateTicket>) -> Result<Created<Ticket>> {
let title = input.validated_title()?;
let title = persistent_title(&title)?;
let db = db.default_connection().map_err(database_error)?;
// Only a successful query that returns no row means the store is full.
let ticket = Ticket::insert(&db, title)
.await
.map_err(database_error)?
.ok_or_else(|| abort_with(409, "Ticket store is full."))?;
Ok(Created(ticket))
}
#[derive(Deserialize)]
// Serde allows only the declared fields to change. The ID remains server-owned.
#[serde(deny_unknown_fields)]
struct PatchTicket {
#[serde(default, deserialize_with = "present_string")]
title: Option<String>,
#[serde(default, deserialize_with = "present_string")]
status: Option<String>,
}
// The decoder runs only for a supplied field, so null cannot be treated as omission.
fn present_string<'de, D: Deserializer<'de>>(value: D) -> std::result::Result<Option<String>, D::Error> {
String::deserialize(value).map(Some)
}
fn patch_input(value: Value) -> Result<PatchTicket> {
let bad_patch = || InvalidInput::new().with("ticket", "Send an object with title or status as strings.");
if !value.is_object() {
return Err(bad_patch().into());
}
serde_json::from_value(value).map_err(|_| bad_patch().into())
}
async fn update(
db: Inject<DatabaseManager>,
Params(id): Params<u32>,
Json(value): Json<Value>,
) -> Result<Json<Ticket>> {
positive_id(id)?;
// Validate the entire object before writing so an invalid status cannot leave a partial update.
let input = patch_input(value)?;
let title = input.title.as_deref().map(validated_title).transpose()?;
let title = title.as_deref().map(persistent_title).transpose()?;
let status = input.status.as_deref();
if title.is_none() && status.is_none() {
return Err(InvalidInput::new()
.with("ticket", "Provide a title or a status.")
.into());
}
if status.is_some_and(|value| !matches!(value, "open" | "closed")) {
return Err(InvalidInput::new()
.with("status", "Status must be open or closed.")
.into());
}
let db = db.default_connection().map_err(database_error)?;
let ticket = Ticket::update(&db, i64::from(id), title, status)
.await
.map_err(database_error)?
.ok_or_else(|| abort_with(404, "Ticket not found."))?;
Ok(Json(ticket))
}
async fn delete(db: Inject<DatabaseManager>, Params(id): Params<u32>) -> Result<NoContent> {
positive_id(id)?;
let db = db.default_connection().map_err(database_error)?;
if !Ticket::delete(&db, i64::from(id)).await.map_err(database_error)? {
return Err(abort_with(404, "Ticket not found."));
}
Ok(NoContent)
}
fn persistent_title(title: &str) -> Result<&str> {
if title.contains('\0') {
return Err(InvalidInput::new()
.with("title", "The title must not contain NUL.")
.into());
}
Ok(title)
}
fn positive_id(id: u32) -> Result<()> {
if id == 0 {
return Err(abort_with(400, "Ticket ID must be positive."));
}
Ok(())
}
const TICKET_BODY_LIMIT: usize = 4096;
const MAX_TITLE_LENGTH: usize = 120;
#[derive(Deserialize, Validate)]
struct CreateTicket {
title: String,
}
#[derive(Serialize)]
struct TicketPreview {
title: String,
}
async fn preview(Json(input): Json<CreateTicket>) -> Result<Json<TicketPreview>> {
Ok(Json(TicketPreview {
title: input.validated_title()?,
}))
}
impl CreateTicket {
fn validated_title(&self) -> Result<String> {
validated_title(&self.title)
}
}
fn validated_title(value: &str) -> Result<String> {
let title = value.trim();
let problem = if title.is_empty() {
"Enter a ticket title."
} else if title.chars().count() > MAX_TITLE_LENGTH {
"The title must have at most 120 Unicode scalar values."
} else {
return Ok(title.to_owned());
};
Err(InvalidInput::new().with("title", problem).into())
}
#[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);
}
#[test]
fn title_validation_counts_trimmed_unicode_scalars() {
let title = "🦀".repeat(120);
let valid = CreateTicket {
title: format!(" {title} "),
};
assert_eq!(valid.validated_title().expect("120 scalars"), title);
let invalid = CreateTicket {
title: format!("{title}🦀"),
};
assert_eq!(invalid.validated_title().expect_err("121 scalars").status(), 422);
let blank = CreateTicket {
title: "\u{00a0}\t".into(),
};
assert_eq!(blank.validated_title().expect_err("blank").status(), 422);
}
}
Write the changes to PostgreSQL
Replace src/routes/api/store.rs. The input to UPDATE is passed as bound parameters. For an omitted field, COALESCE takes the value from the current row. Concurrent changes to different fields both survive because PostgreSQL locks the row and reevaluates the update after waiting. If both requests change the same field, the last successful change in lock order wins. Deletion uses one statement and checks the affected row count.
use laravel::db::{self, AnyConnection};
use laravel::{Result, abort};
use serde::Serialize;
#[derive(db::FromRow, Serialize)]
pub(super) struct Ticket {
id: i64,
title: String,
status: String,
}
impl Ticket {
// Bound parameters travel separately from the SQL, so user input cannot become query syntax.
pub(super) async fn list(db: &AnyConnection, status: Option<&str>) -> Result<Vec<Self>> {
db::query!(
db,
"SELECT id, title, status FROM tickets
WHERE ({status}::text IS NULL OR status = {status})
ORDER BY id LIMIT 32"
)
.select_as()
.await
}
pub(super) async fn get(db: &AnyConnection, id: i64) -> Result<Option<Self>> {
db::query!(db, "SELECT id, title, status FROM tickets WHERE id = {id}")
.select_one_as()
.await
}
pub(super) async fn insert(db: &AnyConnection, title: &str) -> Result<Option<Self>> {
// The lock serializes slot allocation and is released when the transaction ends.
db.transaction(async |tx| {
db::query!(tx, "SELECT pg_advisory_xact_lock(128991, 1)")
.statement()
.await?;
// At READ COMMITTED this statement sees the insert committed before the lock was acquired.
db::query!(
tx,
"INSERT INTO tickets (slot, title)
SELECT n, {title} FROM generate_series(1, 32) AS slots(n)
WHERE NOT EXISTS (SELECT 1 FROM tickets WHERE slot = n)
ORDER BY n LIMIT 1
RETURNING id, title, status"
)
.insert_returning_as()
.await
})
.await
}
pub(super) async fn update(
db: &AnyConnection,
id: i64,
title: Option<&str>,
status: Option<&str>,
) -> Result<Option<Self>> {
// COALESCE keeps omitted fields from the current row. A single UPDATE is atomic.
db::query!(
db,
"UPDATE tickets SET title = COALESCE({title}, title),
status = COALESCE({status}, status) WHERE id = {id}
RETURNING id, title, status"
)
.update_returning_as()
.await
}
pub(super) async fn delete(db: &AnyConnection, id: i64) -> Result<bool> {
// A single DELETE is atomic. A query failure is distinct from affecting zero rows.
let deleted = db::query!(db, "DELETE FROM tickets WHERE id = {id}").delete().await?;
Ok(deleted == 1)
}
}
pub(super) fn database_error(_: laravel::Error) -> laravel::Error {
// Keep database error details out of the client response.
abort(500)
}
An empty query result and a database error are separate outcomes for reads and updates. An empty result returns 404, while a database error returns 500. A delete returns 204 only after successfully deleting one row. Creation still locks slot allocation in a transaction. Single UPDATE and DELETE statements already run atomically. The lesson on testing and debugging covers the race for the last slot and a controlled timeout.
Exercise the routes
If the HTTP server is still running, stop it with Ctrl+C. After building, run bash scripts/ticket-db.sh serve ticket_demo 18080 in the first terminal with PG_BIN and TICKET_LAB from lesson 09. No new migration is needed. In the second terminal, api passes -q as the first curl argument to skip settings in .curlrc. The requests use the ID from the POST response.
export CARGO_TARGET_DIR="$PWD/target"
export CARGO_BUILD_BUILD_DIR="$CARGO_TARGET_DIR/build"
export CARGO_INCREMENTAL=0
cargo build --locked --offline
base=http://127.0.0.1:18080/api/tickets
api() {
curl -q -sS --noproxy '*' --max-time 8 -H 'Accept: application/json' "$@"
}
json=(-H 'Content-Type: application/json')
api "$base" | jq -e 'type == "array" and length <= 32'
api "${json[@]}" --data '{"title":" Replace scanner "}' "$base/preview" | jq -e '.title == "Replace scanner"'
created=$(api "${json[@]}" --data '{"title":"Replace scanner","id":900,"status":"closed"}' "$base")
printf '%s\n' "$created" | jq -e '.status == "open" and .id != 900'
id=$(jq -er '.id' <<< "$created")
api "$base/$id" | jq -e '.title == "Replace scanner"'
api -X PATCH "${json[@]}" --data '{"status":"closed"}' "$base/$id" |\
jq -e '.status == "closed" and .title == "Replace scanner"'
api -i -X PATCH "${json[@]}" --data '{"title":null}' "$base/$id"
printf '\n'
api -X PATCH "${json[@]}" --data '{"title":"Replace label printer"}' "$base/$id" |\
jq -e '.status == "closed" and .title == "Replace label printer"'
api "$base?status=closed" | jq -e --argjson id "$id" 'any(.id == $id)'
api -i -X DELETE "$base/$id"
printf '\n'
api -i -X DELETE "$base/$id"
printf '\n'
api -i "$base/$id"
printf '\n'
A successful read, update, and preview returns 200. Creation returns 201. The first delete returns 204 with an empty body. Repeating the delete or reading the deleted ticket returns 404 with Ticket not found.. In the first terminal, stop the HTTP server with Ctrl+C and run bash scripts/ticket-db.sh inspect ticket_demo to check the other tickets. To use the API again, rerun serve there with the same variables.
Truncated JSON returns 400 with a message. A zero ID and an unknown filter also return 400, each with its own message. A negative, nonnumeric, or out-of-range u32 is rejected by the route extractor before a database call. It returns 404 with Not Found. A field with the wrong type or a failed data rule returns 422 with errors. A body over 4096 bytes returns 413 and an unsupported content type returns 415. Both carry a message. If every slot is taken, 409 carries Ticket store is full.. The client-facing 500 excludes SQL, connection details, and internal exceptions.
Summary
Every operation uses the existing ticket table. A partial update retains omitted values, and deleting the same ticket twice reports that the record is missing. Clients can distinguish rejected input, a missing ticket, capacity, and database failure.
References
- Laravel Rust 0.1.4 source —
docs/routing.md,docs/database.md. - Laravel Rust HTTP source —
src/validation/request.rs. - PostgreSQL transaction isolation.