{{announcement.body}}
{{announcement.title}}

Rust Web Development Boilerplate Free with Rocket

DZone 's Guide to

Rust Web Development Boilerplate Free with Rocket

Rocket is a web framework for Rust to write fast and secure web applications. An overview of the Rocket web framework for rust.

· Web Dev Zone ·
Free Resource

Rocket is a web framework for Rust to write fast and secure web applications.

  • It is type-safe, you don't have to deal with string, instead, make use of rust type system.
  • Is boilerplate free, you write just enough code, and Rocket will generate the boilerplate code for you using macros.
  • Easy to use, with simple and intuitive APIs, it claims that it doesn't matter your background, you will find Rocket approachable.
  • And is extensible, you can create your primitives that any Rocket application can use.

Let's take a look at what Rocket offers.

Routing

To route requests to the appropriate request handler. We need to specify the attributes of the route on top of the function that is the request handler.

Rust
 




xxxxxxxxxx
1

Let's take a look at what Rocket offers
 
1
#[get("/")]
2
fn index() -> &str {
3
   "Hello, world!"
4
}


We use macros to specify those attributes, for example, the route index will match against a "GET" request in the Root path. This handler then will return a Hello World message.

Rocket will use the string as the body of a fully formed HTTP response.

Dynamic Params

We can also have dynamic parameters. 

Rust
 




x


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


The hello handler will match against "GET" requests to the path /hello/<name>/<age>. That name will be pass as the name parameter of type String and age of type unsigned integer. Then the handler will return that formatted string. Each parameter must be defined inside brackets in the path, and as parameters to the handler. 

The route will only be called if parsing succeeds. To parse the string, Rocket uses the "FromParam" trait, which you can implement for your own types!

Handling Data

To handle the request body data. For instance, a Post request, we need to tell rocket that we are expecting body data and the parameter that will handle that data.

Rust
 




xxxxxxxxxx
1


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


In this case, the user form will be a Form of type UserLogin. "Form" is a build-in type of rocket that knows how to parse web forms, and User Login is a custom type that we can create. We can use any type that implements the FromData Trait. Rocket already includes implementations of other types such as JSON. Again, the handler only executes if the body data can be parsed correctly.

Request "Guards"

Rocket also has the concept of Request Guard which is another type of parameter that doesn't need to be declared in the route attributes. Those request guards protect the handler from running unless some set of conditions are met by the incoming request.

Rust
 




xxxxxxxxxx
1


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


In this example, we have the custom type ApiKey, that implements the trait FromRequest and for instance, can retrieve the API key from the header and validate the signature. If the API key cannot be validated then the sensitive handler won't run.

Responses

The return type of a request handler can be any type that implements the trait Responder. Rocket provides implementations for common types. 

Rust
 




xxxxxxxxxx
1


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


Responders can also fail with a status code, in which case you can also define an error handler for those status codes using a catch route.

Rust
 




xxxxxxxxxx
1


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


Running the App

Here is the code to configure and run a rocket application.

Rust
 




xxxxxxxxxx
1


 
1
rocket::ignite()
2
   .mount("/base", routes![index, another])
3
   .launch();


First, you create an instance of Rocket by using the ignite function from rocket. Then you add the routes by using the mount function, specify the base path or a namespace for your routes, and then a set of routes using the routes! macro. And finally, you start the server by calling launch.

Check out the video to learn more about Rocket:

  • A couple of things to consider before using Rocket
  • Building a Hello World service
  • Define custom configuration for the app
  • Building a TODO service with a Postgres database

Rocket official: https://rocket.rs/

Topics:
rest, rust

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}