» Rust: Build a REST API with Rocket » 2. Development » 2.1 Initial Version

Initial Version

Create a package

Run the cargo new command:

cargo new lr_rest_books_rust --bin

We’re passing --bin because we’re making a binary program: if we were making a library, we’d pass --lib.

Or, if you want to create a binary Cargo package in the current directory:

cargo init

This command creates start files, including the Cargo.toml file, where you can list the dependencies you add for tracking.

Add Rocket framework

Run the cargo add command:

cargo add rocket

Or, add Rocket framework in Cargo.toml:

@@ -6,3 +6,4 @@ edition = "2021"
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
 [dependencies]
+rocket = "0.5.0"

Update src/main.rs:

#[macro_use]
extern crate rocket;

use rocket::response::content;

#[get("/ping")]
fn ping() -> content::RawJson<&'static str> {
    content::RawJson("{\"message\": \"pong\"}")
}

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

Run the program like this:

cargo run

You will get result lines like below:

🔧 Configured for debug.
   >> address: 127.0.0.1
   >> port: 8000
   >> workers: 12
   >> max blocking threads: 512
   >> ident: Rocket
   >> IP header: X-Real-IP
   >> limits: bytes = 8KiB, data-form = 2MiB, file = 1MiB, form = 32KiB, json = 1MiB, msgpack = 1MiB, string = 8KiB
   >> temp dir: /var/folders/wx/hdjympxj7h3_ntwgzbhddyr40000gn/T/
   >> http/2: true
   >> keep-alive: 5s
   >> tls: disabled
   >> shutdown: ctrlc = true, force = true, signals = [SIGTERM], grace = 2s, mercy = 3s
   >> log level: normal
   >> cli colors: true
📬 Routes:
   >> (ping) GET /ping
📡 Fairings:
   >> Shield (liftoff, response, singleton)
🛡️ Shield:
   >> Permissions-Policy: interest-cohort=()
   >> X-Content-Type-Options: nosniff
   >> X-Frame-Options: SAMEORIGIN
🚀 Rocket has launched from http://127.0.0.1:8000

Your API server is runnong on port 8000 now.

Try to hit the endpoint /ping with curl command:

curl http://localhost:8000/ping

It shows:

{"message": "pong"}

Nice! Your server is doing well.

PrevNext