Routes
How files in api/ become HTTP routes, who may call them, what handlers take and return, and their limits.
A route is a pub async fn in a file under api/, with an attribute that names its HTTP method and who may call it. The file's path is the URL path. This page covers paths, auth, what a handler takes and returns, errors and limits. For WebSockets, see WebSockets.
Files become paths
| File | Serves |
|---|---|
api/health.rs | /api/health |
api/visits/index.rs | /api/visits |
api/visits/[id].rs | /api/visits/{id} |
api/gates/[lane]/open.rs | /api/gates/{lane}/open |
api/files/[...path].rs | /api/files/{*path}: everything after /api/files/, as path |
index.rsserves its folder's path.[name]is a path parameter.[...name]takes the rest of the path.- Files and folders starting with
_or.aren't read. Shared code (models, queries, rules like plate matching) goes undersrc/, as the crate's own modules. - One file can hold several methods:
get,post,put,patchanddeletehandlers side by side.
The build fails when two files serve the same method and path, when a handler isn't pub async fn, when a route sits outside api/, and when a trigger sits inside it.
A route
// api/visits/[id].rs → GET /api/visits/{id}
use floor::prelude::*;
use crate::model::Visit;
#[get(can = "visits:read")]
pub async fn get(cx: Cx, Path(id): Path<i64>) -> Result<Json<Visit>> {
let visit: Visit = sqlx::query_as("select id, plate, lane_id, status from visits where id = $1 and organization = $2")
.bind(id)
.bind(cx.org()?)
.fetch_optional(cx.db())
.await?
.or_not_found()?;
Ok(Json(visit))
}The attributes are #[get], #[post], #[put], #[patch] and #[delete]. use floor::prelude::*; brings them in with everything else a handler file needs.
Who may call it
Every route says who may call it, once. A route that doesn't fails to compile. The backend checks the caller before the handler runs.
| Attribute | Lets in |
|---|---|
#[get(public)] | Anyone, with or without a token |
#[get(signed_in)] | Any valid Floor token for the project: a user's access token or a service client's |
#[get(role = "admin")] | Callers with that role |
#[get(roles = "admin, guard")] | Callers with any of those roles |
#[get(can = "visits:read")] | Callers whose roles permissions.rs allows visits:read |
#[post(device)] | The project's devices, by the token Floor's device protocol gave them |
- The token comes as
Authorization: Bearer …. floord checks it: Floor's signature, unexpired, and issued for this project. The answer is kept for a minute, or less if the token expires sooner. - No token, or one Floor doesn't vouch for, is a 401. A valid token without the role or permission is a 403.
- Devices are let in only where a route says
device. A device token on any other route is a 403. On adeviceroute,cx.device()is the caller's hardware id. cannames a permission frompermissions.rs. Acanthe file doesn't define stops the backend at start and fails its tests. See Realtime and permissions.
Inside the handler, cx.user() is the caller (sub, kind, org, roles, email, name), cx.org() their organization, and cx.can("gates:open") checks a permission in code.
What a handler takes
cx: Cx comes first, then up to six extractors in any order:
| Extractor | Gives |
|---|---|
Json<T> | The body as JSON. A body that doesn't fit T is a 400 naming the field; an empty body is a 400 |
Query<T> | The query string, ?before=120&limit=20. A repeated key fills a Vec field: ?vehicle=1&vehicle=2 is vehicle: Vec<i64> |
RawQuery | The query string as it came, for parsing by hand |
Multipart | A multipart/form-data body (a browser's FormData): its fields and files |
Path<T> | Path parameters: Path<i64> for one, Path<(i64, String)> for two in order, or a struct with fields named after them |
Body | The raw body as bytes |
Headers | The request's headers |
Json<T>, Query<T> and Path<T> need T: Deserialize + Type. #[derive(Deserialize, Type)] gives both; Type describes T for the dashboard client.
// api/visits/index.rs → GET /api/visits?before=…&limit=…
#[derive(Deserialize, Type)]
pub struct Page {
#[serde(default)]
before: Option<i64>,
#[serde(default = "fifty")]
limit: i64,
}
fn fifty() -> i64 {
50
}
#[get(can = "visits:read")]
pub async fn get(cx: Cx, Query(page): Query<Page>) -> Result<Json<Visits>> {
// …
}A path parameter is parsed as a number when it looks like one, else as a string. GET /api/visits/abc on a Path<i64> route is a 400.
An upload form, files and fields together:
// api/vehicles/[id]/documents.rs → POST /api/vehicles/{id}/documents
#[post(can = "vehicles:write", body = "20mb")]
pub async fn post(cx: Cx, Path(id): Path<i64>, form: Multipart) -> Result<Created<Json<Doc>>> {
let file = form.file("document").ok_or_else(|| Error::bad_request("attach the document"))?;
let title = form.text("title").unwrap_or_default();
let key = format!("vehicles/{id}/{}", uuid::Uuid::now_v7());
// Small files can go through the backend; large ones are better uploaded straight to
// storage with cx.upload_url.
// …
}The whole body is read before the handler runs, so give the route a body limit that fits the
largest file. The generated client takes a FormData for it.
What it returns
| Return | Status |
|---|---|
Result<Json<T>> | 200, with T as JSON |
Result<Created<T>> | 201, with T as JSON |
Result<NoContent> or Result<()> | 204 |
Result<String> or Result<&'static str> | 200, as text/plain |
Result<Response> | Whatever you build: Response::new(202, "queued").header("location", "/api/visits/9") |
Json<T> and Created<T> need T: Serialize + Type. A hand-built Response works, but the dashboard client can't say what it returns.
Errors
A handler returns floor::Result<T>. Each error is a status and a message, sent as {"error": "…"}:
| Error | Status |
|---|---|
Error::bad_request("that isn't a plate") | 400 |
Error::forbidden("…") | 403 |
Error::not_found("…"), option.or_not_found()? | 404 |
Error::conflict("the lane is closed") | 409 |
| A failed call to Floor (a device command, a publish) | 502 |
Anything else (anyhow::Error, a bug) | 500. It's logged, and the caller sees only internal error |
sqlx errors map themselves through ?:
- no row (
fetch_onefound nothing) is a 404; - a unique violation is a 409,
that already exists; - a foreign key violation is a 409.
So registering the same plate twice answers 409 without any code for it.
Limits
A request body is at most 1 MiB, and a handler has 60 seconds. A route can change either:
// A plate and a few fields: a small body and a short time.
#[post(can = "vehicles:write", body = "16kb", timeout = "10s")]
pub async fn post(cx: Cx, Json(v): Json<NewVehicle>) -> Result<Created<Vehicle>> {
// …
}bodyis 1kb to 1gb (kb,mb,gb, or bytes). A larger body is a 413 before it's read.timeoutis 1s to 30m (s,m,h). Past it, the handler is stopped and the caller gets a 504.- A handler that panics is a 500. The backend keeps serving.
For files, don't raise body: hand the caller a signed upload URL with cx.upload_url so the bytes go straight to blob storage.
Calls from devices
A gate controller can call its backend over HTTP with its Floor device token:
// api/devices/heartbeat.rs → POST /api/devices/heartbeat
#[post(device)]
pub async fn post(cx: Cx) -> Result<NoContent> {
let hw = cx.device()?;
sqlx::query("insert into heartbeats (device) values ($1)")
.bind(hw)
.execute(cx.db())
.await?;
Ok(NoContent)
}Most device traffic goes over MQTT instead; see Triggers.
Formatting
The build includes handler files by path, so cargo fmt doesn't reach them. Format them with:
find api on jobs -name '*.rs' -exec rustfmt --edition 2024 {} +See also Attributes, Handlers and Errors.