Building a To-Do API with Rocket and Diesel
Prerequisites
To follow this tutorial, you should have:
- Familiarity with the Rust programming language and Cargo build system
- Basic understanding of database connections
- Ability to start a development project in your preferred environment
Setting Up the Project
Create a new project using Cargo:
cargo new todo_api
Add dependencies to Cargo.toml
:
[dependencies]
rocket = "0.5.0-rc.1"
diesel = { version = "1.4.7", features = ["sqlite"] }
Install Diesel CLI:
cargo install diesel_cli --no-default-features --features sqlite
Creating Migrations with Diesel
Run diesel setup
to create a migrations directory:
diesel setup
Create a new migration:
diesel migration generate create_tasks
Write SQL statements for creating and dropping tasks table in up.sql
and down.sql
files:
-- up.sql
CREATE TABLE tasks (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
completed BOOLEAN NOT NULL DEFAULT FALSE
);
-- down.sql
DROP TABLE tasks;
Apply migration:
diesel migration run
Writing API Logic in Rust
Create a new module: database.rs
// database.rs
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
pub struct Database {
conn: SqliteConnection,
}
impl Database {
pub fn new() -> Self {
// Initialize database connection
}
pub fn create_task(&self, title: &str) {
// Create a new task
}
pub fn get_tasks(&self) -> Vec<Task> {
// Get all tasks
}
}
Routing API with Rocket
Import Rocket and define routes:
// main.rs
#[macro_use] extern crate rocket;
use rocket::Request;
use rocket::response::content;
mod database;
#[get("/tasks")]
fn get_tasks(db: database::Database) -> Vec<Task> {
db.get_tasks()
}
#[post("/tasks", data = "<r>")]
fn create_task(db: database::Database, title: &str) -> String {
db.create_task(title);
"Task created successfully!".to_string()
}
fn main() {
rocket::ignite().mount("/", routes![get_tasks, create_task]).launch();
}
Note: I’ve added some code snippets to illustrate the steps, but you may need to complete the implementation details.