Learn ROCKET with Real Code Examples
Updated Nov 27, 2025
Code Sample Descriptions
1
Rocket Simple REST API
#[macro_use] extern crate rocket;
use rocket::serde::{json::Json, Deserialize, Serialize};
use std::sync::Mutex;
#[derive(Serialize, Deserialize, Clone)]
struct Todo {
id: u32,
title: String,
completed: bool,
}
struct AppState {
todos: Mutex<Vec<Todo>>,
}
#[get("/todos")]
fn get_todos(state: &rocket::State<AppState>) -> Json<Vec<Todo>> {
let todos = state.todos.lock().unwrap();
Json(todos.clone())
}
#[post("/todos", format = "json", data = "todo")]
fn add_todo(todo: Json<Todo>, state: &rocket::State<AppState>) {
let mut todos = state.todos.lock().unwrap();
todos.push(todo.into_inner());
}
#[launch]
fn rocket() -> _ {
rocket::build()
.manage(AppState { todos: Mutex::new(Vec::new()) })
.mount("/", routes![get_todos, add_todo])
}
Demonstrates a simple Rocket application with routes for listing and creating Todo items using type-safe request handling.