Unlock the Power of Rust for Web Development

Getting Started with Rocket

Before we dive in, ensure you have Rust installed on your machine by running rustup in your terminal. If you encounter any issues, refer to the rustup installation instructions. With rustup installed, we can use Cargo to create a new Rust project. Run the following command to create a new Rust app named rocket-web:

cargo new rocket-web --bin

Configuring Our App

Next, navigate to the new project directory and configure Rust nightly as our project toolchain using the following command:

rustup override set nightly

This is necessary because Rocket uses unstable features of Rust. Then, add Rocket as a dependency in your cargo.toml file:

[dependencies]
rocket = "0.5.0-rc.1"

And import it in your main.rs file:

extern crate rocket;

Creating Our First Rocket Route

Now that we have our project set up, let’s create our first Rocket route. We’ll start by importing the Json type from the rocket::response::content macro:

use rocket::response::content::Json;

Then, define a route using the #[get("/hello")] attribute and specify its return type as Json :

#[get("/hello")]
fn hello() -> Json<'static> {
    Json(json!({
        "status": "success",
        "message": "Hello API!",
    }))
}

When a GET request is sent to our /hello route, it will return a JSON response with a body of 'status': 'uccess' and 'message': 'Hello API!'.

Handling POST Requests

Rocket allows us to return various types, including String, Status, and Template. Let’s create a POST route to add book information to a dummy database. We’ll define a Book struct to represent the data we expect from our user:

struct Book {
    title: String,
    author: String,
}

Then, create a POST route using the #[post("/book")] attribute and specify its return type as String:

#[post("/book", data = "<r>")]
fn add_book(r: Json<Book>) -> String {
    format!("Added book: {}", r.title)
}

Handling 404 Routes

To handle 404 responses for nonexistent routes, we’ll create a new route named not_found. We’ll use the #[catch(404)] attribute to tell Rocket to return a 404 error when this route is called:

#[catch(404)]
fn not_found() -> &'static str {
    "Not found"
}

Rendering HTML Templates

Rocket also supports rendering HTML templates using the Handlebars templating language. Let’s create a new GET route with attribute #[get("/")] and return a Template. We’ll create a Context struct to define the variables our template file expects and use Serde to implement Serialize on our struct:

use rocket_contrib::templates::Template;

struct Context {
    title: String,
}

impl Serialize for Context {
    fn serialize(&self, json: &mut serde_json::Serializer) -> Result {
        json.object(|json| {
            json.key("title").value(&self.title)?;
            Ok(())
        })
    }
}

#[get("/")]
fn index() -> Template<Context> {
    Template::render("index", Context { title: "Hello World".to_string() })
}

We’ve covered the basics of Rocket, response types, error handling, and rendering HTML templates.

Leave a Reply