We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

Skip to content
devvkit
$devvkit learn --librarie rocket-guide

Rocket Guide

[rust][http][web][type-safe]
Rust
Install
cargo add rocket
# Rocket uses nightly; run:
# rustup override set nightly

Rocket emphasizes developer experience with proc-macro-based routing, automatic request type-checking via form guards and data guards, and compile-time URI generation.

Rocket's core features: `#[get("/<id>")]` routing, `FromForm` derive for form parsing, `serde` integration for JSON, fairings (Rocket's middleware), and templating via Tera or Handlebars.

Rocket v0.5+ stabilizes on stable Rust. You no longer need nightly. It adds support for WebSockets, async stream responders, and improved streaming responses.

Setup

Basic server· Hello world.
#[macro_use] extern crate rocket;

#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
}

Routing

Route segments· Dynamic URL segments.
#[get("/hello/<name>/<age>")]
fn hello(name: &str, age: u8) -> String {
    format!("Hello, {} year old named {}!", age, name)
}
Query parameters· Query strings.
#[derive(FromForm)]
struct Search { q: String, page: Option<u32> }

#[get("/search?<search..>")]
fn search(search: Search) -> String {
    format!("Searching for: {}", search.q)
}

Forms

Form handling· Form submission.
#[derive(FromForm)]
struct Login { username: String, password: String }

#[post("/login", data = "<form>")]
fn login(form: Form<Login>) -> String {
    format!("Welcome, {}!", form.username)
}
JSON handling· Request/response JSON.
#[derive(Deserialize)]
struct CreateUser { name: String, email: String }

#[post("/users", data = "<user>")]
fn create_user(user: Json<CreateUser>) -> Json<User> {
    let created = create_in_db(user.into_inner());
    Json(created)
}

State

Managed state· Application-wide state.
struct HitCount { count: AtomicUsize }

#[get("/count")]
fn count(hit_count: &State<HitCount>) -> String {
    format!("Hits: {}", hit_count.count.load(Ordering::Relaxed))
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .manage(HitCount { count: AtomicUsize::new(0) })
        .mount("/", routes![count])
}

Fairings

Fairing· Middleware-like hooks.
struct Logger;

#[rocket::async_trait]
impl Fairing for Logger {
    fn info(&self) -> Info { Info { name: "Logger", kind: Kind::Request } }

    async fn on_request(&self, req: &mut Request<'_>, _: &mut Data<'_>) {
        println!("Request: {} {}", req.method(), req.uri());
    }
}

rocket::build().attach(Logger)

Templates

Templates· Render with Tera.
#[get("/")]
fn index() -> Template {
    let context = context! { title: "Hello", items: vec!["a", "b"] };
    Template::render("index", context)
}

// Rocket.toml or:
rocket::build().mount("/", routes![index]).attach(Template::fairing())