Rocket
02 / 02

Rocket Fundamentals: Routes, Guards & Type Safety

Rocket: Routes, Guards & Type Safety

Rocket is a Rust web framework focused on ease of use, type safety, and speed -- leaning heavily on Rust's type system and procedural macros to catch a wide range of configuration mistakes at compile time.

Attribute-Macro Routing

#[get("/users/<id>")]
fn get_user(id: u32) -> Json<User> {
    Json(find_user(id))
}

// The <id> path segment is automatically parsed into u32,
// and the compiler verifies the route's declared parameter
// matches the handler's actual signature

Request Guards

struct ApiKey(String);

#[rocket::async_trait]
impl<'r> FromRequest<'r> for ApiKey {
    type Error = ();
    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
        match req.headers().get_one("x-api-key") {
            Some(key) => Outcome::Success(ApiKey(key.to_string())),
            None => Outcome::Error((Status::Unauthorized, ())),
        }
    }
}

#[get("/admin")]
fn admin_panel(_key: ApiKey) -> &'static str { "welcome" }

Fairings: Rocket's Middleware

A Fairing hooks into Rocket's request/response lifecycle at specific points -- before a request is handled, after a response is generated -- used for logging, CORS, or request timing.

Managed State

rocket::build().manage(db_pool).mount("/", routes![get_user])

#[get("/users/<id>")]
fn get_user(id: u32, pool: &State<DbPool>) -> Json<User> { ... }

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free