Here is a sample code snippet for creating a REST API in Rust using the popular web framework Rocket:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; use rocket_contrib::json::{Json, JsonValue}; #[derive(Serialize, Deserialize)] struct Person { name: String, age: u8, } #[post("/person", format = "json", data = "<person>")] fn add_person(person: Json<Person>) -> JsonValue { json!({ "message": format!("Added person: {} with age: {}", person.name, person.age) }) } #[get("/person/<name>")] fn get_person(name: String) -> Json<Person> { let person = Person { name, age: 30, // assuming a default age }; Json(person) } fn main() { rocket::ignite() .mount("/", routes![add_person, get_person]) .launch(); } |
This code defines two routes: add_person for adding a new person with a name and age, and get_person for retrieving the details of a person by name.
To run this code, you will need to add the following dependencies to your Cargo.toml file:
1 2 3 4 5 | [dependencies] rocket = "0.5.0-rc.1" rocket_contrib = "0.5.0-rc.1" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" |
Then, you can build and run the code using the following command:
1 | cargo run |