Simple REST API - Rocket Typing CST Test
Loading…
Simple REST API — Rocket Code
Demonstrates a simple Rocket application with routes for listing and creating Todo items using type-safe request handling.
#[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])
}Rocket Language Guide
Rocket is a Rust-based web framework designed for type-safe, fast, and secure web applications and APIs.
Primary Use Cases
- ▸Building type-safe web APIs
- ▸High-performance backend services
- ▸Server-side applications with Rust safety guarantees
- ▸RESTful and GraphQL APIs
- ▸Applications requiring strict compile-time checks
Notable Features
- ▸Type-safe routing and request guards
- ▸Built-in JSON and form data handling
- ▸Asynchronous request handling
- ▸Template rendering support (Tera, Handlebars)
- ▸Fairings and request/response hooks for extensibility
Origin & Creator
Created by Sergio Benitez in 2016, Rocket is maintained by the Rust community and open-source contributors.
Industrial Note
Rocket is particularly suited for high-performance web applications where safety, speed, and Rust’s memory guarantees are critical, such as fintech, embedded web services, and high-throughput APIs.