Skip to Content

Build your first backend

Make a small gate backend with a table, two routes and a test, run it against Floor, and deploy it.

At the end of this guide you have a backend that registers vehicles for a gate: a migration, a POST and a GET route guarded by permissions, a test, and a running copy connected to Floor. You need the CLI, Cargo and Postgres set up as in Install, and a project on Floor with a development environment. Here the project is gate and its environment gate-dev (floor projects add-env gate dev makes it; see Environments).

1. Make the crate

floor new gate
cd gate

floor new prints each file it writes:

making gate:
  gate/Cargo.toml
  gate/floor.toml
  gate/.cargo/config.toml
  gate/build.rs
  gate/src/lib.rs
  gate/src/main.rs
  gate/api/health.rs
  gate/permissions.rs
  gate/channels.rs
  gate/db/migrations/0001_init.sql
  gate/tests/app.rs
  gate/.gitignore
  gate/rust-toolchain.toml

The crate builds as it is. Its parts:

  • Cargo.toml depends on floor (the usefloor crate from crates.io) twice: as a dependency, and as a build-dependency with the build feature. serde, serde_json and sqlx are the crate's own dependencies, because their derives and macros look for them by name.
  • build.rs is fn main() { floor::build::generate(); }. It reads api/, on/ and jobs/ and generates the app. src/lib.rs includes it with floor::app!();, and src/main.rs runs it with floor::run(gate::app()).
  • api/health.rs is GET /api/health, open to anyone, answering ok.
  • floor.toml says which project the backend belongs to and where it's served when deployed.

2. Run it against Floor

floor dev --project gate-dev
floor dev: gate for gate-dev
  link      wss://usefloor.dev/v1/link
  http      http://127.0.0.1:3000
  database  127.0.0.1:5432/gate_dev

✓ ready in 11.5 s (build 10.4 s)

floor dev made a gate_dev database on your local Postgres, applied the migrations, built the backend, and started it connected to the gate-dev project. The first build takes longest. Keep it running, and in another terminal:

curl http://127.0.0.1:3000/api/health
ok

floor dev logs a line for the request: GET /api/health 200 0.1 ms.

3. Add a table

0001_init.sql already ran in gate_dev, and a migration that ran is never edited. Add a new file, db/migrations/0002_vehicles.sql:

create table vehicles (
    id bigserial primary key,
    organization text not null,
    plate text not null,
    unique (organization, plate)
);

Save it. floor dev rebuilds and restarts the backend, which applies the new migration as it starts.

4. Say who may do what

Replace the example in permissions.rs:

floor::permissions! {
    vehicles: { read: [admin, guard], write: [admin] },
}

Admins and guards may read vehicles. Only admins may register them. The roles are the ones Floor's sign-in gives your project's users.

5. Add the routes

Make the route file with the CLI:

floor new route vehicles --method post --can vehicles:write
floor new route vehicles --can vehicles:read

The first command writes api/vehicles.rs with a post handler; the second adds a get to the same file. Both return placeholder JSON. Replace the file with:

//! /api/vehicles: the caller's organization's vehicles.

use floor::prelude::*;

#[derive(Deserialize, Type)]
pub struct NewVehicle {
    plate: String,
}

#[derive(Serialize, sqlx::FromRow, Type)]
pub struct Vehicle {
    id: i64,
    plate: String,
}

#[post(can = "vehicles:write")]
pub async fn post(cx: Cx, Json(v): Json<NewVehicle>) -> Result<Created<Vehicle>> {
    let plate = v.plate.trim().to_uppercase();
    if plate.len() < 3 {
        return Err(Error::bad_request("that isn't a plate"));
    }
    let vehicle: Vehicle = sqlx::query_as(
        "insert into vehicles (organization, plate) values ($1, $2) returning id, plate",
    )
    .bind(cx.org()?)
    .bind(&plate)
    .fetch_one(cx.db())
    .await?;
    Ok(Created(vehicle))
}

#[get(can = "vehicles:read")]
pub async fn get(cx: Cx) -> Result<Json<Vec<Vehicle>>> {
    let vehicles: Vec<Vehicle> =
        sqlx::query_as("select id, plate from vehicles where organization = $1 order by id")
            .bind(cx.org()?)
            .fetch_all(cx.db())
            .await?;
    Ok(Json(vehicles))
}

What each part does:

  • Json(v): Json<NewVehicle> parses the body. A body that doesn't fit is a 400 that names the field.
  • cx.org() is the caller's organization, so one customer never sees another's vehicles.
  • Created(…) answers 201 with the JSON. Error::bad_request answers 400.
  • The same plate twice breaks the unique constraint, and sqlx's unique violation becomes a 409.
  • #[derive(Type)] describes the types for the dashboard's TypeScript client.

Save. Once floor dev says ready, try the route without a token:

curl -i http://127.0.0.1:3000/api/vehicles
HTTP/1.1 401 Unauthorized
…
{"error":"sign in first"}

The backend refused it before the handler ran.

6. Test it

Add a test to tests/app.rs:

use serde_json::json;

#[tokio::test]
async fn admins_register_vehicles_and_guards_read_them() {
    let t = TestApp::start(gate::app()).await;
    let admin = t.sign_in(&["admin"]);
    let guard = t.sign_in(&["guard"]);

    let r = t.post("/api/vehicles", Some(&admin), json!({ "plate": "LEB-4821" })).await;
    assert_eq!(r.status, 201, "{}", r.text());

    // The same plate again is a conflict, not a 500.
    let again = t.post("/api/vehicles", Some(&admin), json!({ "plate": "leb-4821" })).await;
    assert_eq!(again.status, 409);

    // Guards read vehicles but don't register them.
    let denied = t.post("/api/vehicles", Some(&guard), json!({ "plate": "ABC-123" })).await;
    assert_eq!(denied.status, 403);

    let list: Vec<serde_json::Value> = t.get("/api/vehicles", Some(&guard)).await.json();
    assert_eq!(list.len(), 1);
    t.close().await;
}

Run the tests:

floor test

TestApp made a fresh database, applied both migrations, and stood in for Floor: sign_in gave tokens for users with those roles in the organization test-org. Both tests pass:

running 2 tests
test it_answers ... ok
test admins_register_vehicles_and_guards_read_them ... ok

7. Deploy it

floor.toml says where the backend is served:

project = "gate"

[backend]
mount = "gate.example.com/api"
health = "/api/health"
memory_mb = 128

Set mount to one of the project's hostnames and the path the backend serves under, and make sure the project has a database (floor db create gate). Then:

floor deploy

floor deploy builds the backend on your machine (cargo build --release --locked) and ships it as a release. Floor runs the migrations against the project's database, starts the new version, waits for /api/health, and switches traffic to it. Deploys from GitHub are set up once per repo; see Deploy.

Next

  • Routes: paths, auth, extractors, errors and limits.
  • Triggers: MQTT from the gate's devices, ticks and jobs.
  • The dashboard client: call these routes from TypeScript with types.

On this page