Latest Release: 🎉 0.5.1 (May 22, 2024)



Type Safe Icon (helmet)

Type Safe

Type safety turned up to 11 means security and robustness come at compile-time. Learn More
Boilerplate Free Icon (robot-free)

Boilerplate Free

Spend your time writing code that really matters and let Rocket handle the rest. See Examples
Easy To Use Icon (sun)

Easy To Use

Simple, intuitive APIs make Rocket approachable, no matter your background. Get Started
Extensible Icon (telescope)

Extensible

Create your own first-class primitives that any Rocket application can use. See How

Hello, Rocket!


This is a complete Rocket application. It does exactly what you would expect. If you were to visit /hello/John/58, you’d see:

1
Hello, 58 year old named John!

If someone visits a path with an <age> that isn’t a u8, Rocket doesn’t naively call hello. Instead, it tries other matching routes or returns a 404.

1
2
3
4
5
6
7
8
9
10
11
#[macro_use] extern crate rocket;

#[get("/hello/<name>/<age>")]
fn hello(name: &str, age: u8) -> String {
    format!("Hello, {} year old named {}!", age, name)
}

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

Forms? Check!


Form handling is simple, declarative, and complete: derive FromForm for your structure and set the data parameter to a Form type. Rocket automatically parses and validates the form data into your structure and calls your function.

File uploads? A breeze with TempFile. Bad form request? Rocket doesn’t call your function! Need to know what went wrong? Use a data parameter of Result! Want to rerender the form with user input and errors? Use Context!

1
2
3
4
5
6
7
8
9
10
11
#[derive(FromForm)]
struct Task<'r> {
    #[field(validate = len(1..))]
    description: &'r str,
    completed: bool,
}

#[post("/", data = "<task>")]
fn new(task: Form<Task<'_>>) -> Flash<Redirect> {
    Flash::success(Redirect::to(uri!(home)), "Task added.")
}

JSON, Always On


Rocket has first-class support for JSON, right out of the box. Simply derive Deserialize or Serialize to receive or return JSON, respectively.

Look familiar? Forms, JSON, and all kinds of body data types work through Rocket’s FromData trait, Rocket’s approach to deriving types from body data. A data route parameter can be any type that implements FromData. A value of that type will be deserialized automatically from the incoming request body. You can even implement FromData for your own types!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#[derive(Serialize, Deserialize)]
struct Message<'r> {
    contents: &'r str,
}

#[put("/<id>", data = "<msg>")]
fn update(db: &Db, id: Id, msg: Json<Message<'_>>) -> Value {
    if db.contains_key(&id) {
        db.insert(id, msg.contents);
        json!({ "status": "ok" })
    } else {
        json!({ "status": "error" })
    }
}

Rocket is ready to launch.

Get Started Learn More

Ins and Outs

Discover how Rocket applications are built.

Rocket's main task is to route incoming requests to the appropriate request handler using your application's declared routes. Routes are declared using Rocket's route attributes. The attribute describes the requests that match the route. The attribute is placed on top of a function that is the request handler for that route.

As an example, consider the simple route below:

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

This index route matches any incoming HTTP GET request to /, the index. The handler returns a String. Rocket automatically converts the string into a well-formed HTTP response that includes the appropriate Content-Type and body encoding metadata.

Rocket automatically parses dynamic data in path segments into any desired type. To illustrate, let's use the following route:

1
2
3
4
#[get("/hello/<name>/<age>")]
fn hello(name: &str, age: u8) -> String {
    format!("Hello, {} year old named {}!", age, name)
}

This hello route has two dynamic parameters, identified with angle brackets, declared in the route URI: <name> and <age>. Rocket maps each parameter to an identically named function argument: name: &str and age: u8. The dynamic data in the incoming request is parsed automatically into a value of the argument's type. The route is called only when parsing succeeds.

Parsing is directed by the FromParam trait. Rocket implements FromParam for many standard types, including both &str and u8. You can implement it for your own types, too!

Rocket can automatically parse body data, too!

1
2
3
4
#[post("/login", data = "<login>")]
fn login(login: Form<UserLogin>) -> String {
    format!("Hello, {}!", login.name)
}

The dynamic parameter declared in the data route attribute parameter again maps to a function argument. Here, login maps to login: Form<UserLogin>. Parsing is again trait-directed, this time by the FromData trait.

The Form type is Rocket's robust form data parser. It automatically parses the request body into the internal type, here UserLogin. Other built-in FromData types include Data, Json, and MsgPack. As always, you can implement FromData for your own types, too!

In addition to dynamic path and data parameters, request handlers can also contain a third type of parameter: request guards. Request guards aren't declared in the route attribute, and any number of them can appear in the request handler signature.

Request guards protect the handler from running unless some set of conditions are met by the incoming request metadata. For instance, if you are writing an API that requires sensitive calls to be accompanied by an API key in the request header, Rocket can protect those calls via a custom ApiKey request guard:

1
2
#[get("/sensitive")]
fn sensitive(key: ApiKey) { ... }

ApiKey protects the sensitive handler from running incorrectly. In order for Rocket to call the sensitive handler, the ApiKey type needs to be derived through a FromRequest implementation, which in this case, validates the API key header. Request guards are a powerful and unique Rocket concept; they centralize application policy and invariants through types.

The return type of a request handler can be any type that implements Responder:

1
2
#[get("/")]
fn route() -> T { ... }

Above, T must implement Responder. Rocket implements Responder for many of the standard library types including &str, String, File, Option, and Result. Rocket also implements custom responders such as Redirect, Flash, and Template.

The task of a Responder is to generate a Response, if possible. Responders can fail with a status code. When they do, Rocket calls the corresponding error catcher, a catch route, which can be declared as follows:

1
2
#[catch(404)]
fn not_found() -> T { ... }

Finally, we get to launch our application! Rocket begins dispatching requests to routes after they've been mounted and the application has been launched. These two steps, usually wrtten in a rocket function, look like:

1
2
3
4
#[launch]
fn rocket() -> _ {
    rocket::build().mount("/base", routes![index, another])
}

The mount call takes a base and a set of routes via the routes! macro. The base path (/base above) is prepended to the path of every route in the list, effectively namespacing the routes. #[launch] creates a main function that starts the server. In development, Rocket prints useful information to the console to let you know everything is okay.

1
🚀 Rocket has launched from http://127.0.0.1:8000

And so much more.

An entire ecosystem, built in.

Templating Icon (templating-icon)

Templating

Rocket makes templating a breeze with built-in templating support. Learn More
Cookies Icon (cookies-icon)

Cookies

View, add, or remove cookies, with or without encryption, without hassle. Learn More
WebSockets + Streams Icon (streams-icon)

WebSockets + Streams

Create and return potentially infinite async streams of data with ease. Learn More

Config Profiles Icon (config-icon)

Config Profiles

Configure your application your way for debug, release, or anything else! Learn More
Type-Checked URIs Icon (pencil-icon)

Type-Checked URIs

Never mistype or forget to update a URI again with Rocket's typed URIs. Learn More
Structured Middleware Icon (ship-icon)

Structured Middleware

Fairings are Rocket's simpler approach to structured middleware. Learn More

Database Support Icon (query-icon)

Database Support

Store data with ease with Rocket's built-in ORM agnostic database support. Learn More
Testing Icon (testing-icon)

Testing

Unit and integration test using the comprehensive, built-in testing library. Learn More
Community Icon (globe)

Community

Join an extensive community of 20,000+ Rocketeers that love Rocket. See Dependents

Thank You ❤️

Your support makes Rocket possible.

💎 Diamond

$500/month

💛 Gold

$250/month

🩶 Silver

$100/month

🤎 Bronze

$50/month

❤️ Sponsor Rocket