REST APIs with Rocket for RUST

Excerpts of code snippets to write rust based rest service using the rocket framework.

Add dependencies

#[macro_use] 
extern crate rocket;
extern crate rocket_contrib;
extern crate serde_json;
extern crate log;

Start Server

fn main() {
    rocket::ignite().mount("/", routes![index, send]).launch();
}

Get (Hello World Example)

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

Try it out

curl http://localhost:15188/

POST with untyped object


#[post("/send", format = "application/json", data ="<data>")]
fn send(data: String) -> std::io::Result<String> {
    let data: Value = serde_json::from_str(&data)?;
    if data["message_title"].is_null() {
        warn!("PHEW ! {} is null", "message title");
    }
    Ok(format!("Message recorded: {}", data["data"]))
}

Try it out

curl -X POST -d "{\"data\":1}" -H "content-type:application/json" http://localhost:15188/send

To specify custom port

Create the Rocket.toml file in the application root (where cargo.toml exists)

[development]
address = "localhost"
port = 15188
# workers = [2]
keep_alive = 5
log = "normal"
limits = { forms = 32768 }

[staging]
address = "0.0.0.0"
port = 15188
# workers = [2]
keep_alive = 5
log = "normal"
limits = { forms = 32768 }

[production]
address = "0.0.0.0"
port = 15188
# workers = [2]
keep_alive = 5
log = "critical"
limits = { forms = 32768 }