Answer#
Three results are possible and each needs its own status: a row, no row, and a database error. fetch_optional keeps the first two apart from the third:
use axum::{
body::{to_bytes, Body},
extract::{Path, State},
http::{Request, StatusCode},
routing::get,
Json, Router,
};
use serde::Serialize;
use sqlx::{FromRow, SqlitePool};
use tower::ServiceExt;
#[derive(Serialize, FromRow)]
struct Todo { id: i64, title: String, done: bool }
async fn show(State(db): State<SqlitePool>, Path(id): Path<i64>) -> Result<Json<Todo>, StatusCode> {
sqlx::query_as::<_, Todo>("SELECT id, title, done FROM todos WHERE id = ?")
.bind(id)
.fetch_optional(&db) // Ok(None) when no row matches
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? // a real database failure
.map(Json)
.ok_or(StatusCode::NOT_FOUND) // no row: 404
}
#[tokio::main]
async fn main() {
let db = SqlitePool::connect("sqlite::memory:").await.unwrap();
sqlx::migrate!("./migrations").run(&db).await.unwrap();
sqlx::query("INSERT INTO todos (id, title) VALUES (1, 'write docs')").execute(&db).await.unwrap();
let app = Router::new().route("/todos/{id}", get(show)).with_state(db);
for uri in ["/todos/1", "/todos/2"] {
let res = app.clone().oneshot(Request::get(uri).body(Body::empty()).unwrap()).await.unwrap();
let status = res.status().as_u16();
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("{uri} -> {status} {}", String::from_utf8_lossy(&body));
}
}/todos/1 -> 200 {"id":1,"title":"write docs","done":false}
/todos/2 -> 404 #[derive(FromRow)]maps columns to fields by name..bind(id)fills the?placeholder; the value is never pasted into the SQL text..map(Json)runs only when a row was found;.ok_or(StatusCode::NOT_FOUND)turnsNoneinto 404.
sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio", "sqlite", "migrate", "macros"] }Common mistakes#
- Using
fetch_onefor a lookup by id. A missing row is then an error (RowNotFound) that is easy to turn into a 500 by mistake. - Mapping every database error to 404 to "keep it simple": a broken connection would then look like missing data.
- Selecting
*into a struct. Name the columns, so a new column cannot break the mapping.
Related questions#
How do I get many rows?#
fetch_all returns a Vec; for large results fetch gives a stream. Add LIMIT (see the thread on pagination).
Why ? placeholders here and $1 in other tutorials?#
The placeholder syntax belongs to the database: SQLite uses ?, PostgreSQL uses $1. This thread ran SQLite only.
Sources#
- sqlx documentation: https://docs.rs/sqlx/0.8.6/sqlx/ (read 2026-12-05)