Building a REST API
This tutorial shows you how to build a complete REST API with RustF, including CRUD operations, validation, and error handling.
Overview
We’ll build a REST API for managing blog posts with the following endpoints:
GET /api/posts- List all postsGET /api/posts/{id}- Get a specific postPOST /api/posts- Create a new postPUT /api/posts/{id}- Update a postDELETE /api/posts/{id}- Delete a post
Project Setup
1. Create Controller
Create src/controllers/api/posts.rs:
#![allow(unused)]
fn main() {
use rustf::prelude::*;
use serde::{Deserialize, Serialize};
pub fn install() -> Vec<Route> {
routes![
GET "/api/posts" => list_posts,
GET "/api/posts/{id}" => get_post,
POST "/api/posts" => create_post,
PUT "/api/posts/{id}" => update_post,
DELETE "/api/posts/{id}" => delete_post,
]
}
}
2. Define Data Structures
#![allow(unused)]
fn main() {
#[derive(Serialize, Deserialize, Clone)]
struct Post {
id: Option<i32>,
title: String,
content: String,
author: String,
published: bool,
created_at: Option<String>,
}
#[derive(Deserialize)]
struct CreatePostRequest {
title: String,
content: String,
author: String,
published: Option<bool>,
}
#[derive(Deserialize)]
struct UpdatePostRequest {
title: Option<String>,
content: Option<String>,
author: Option<String>,
published: Option<bool>,
}
}
Implementation
List Posts
#![allow(unused)]
fn main() {
async fn list_posts(ctx: &mut Context) -> Result<()> {
// Parse pagination parameters
let page = ctx.int_query_or("page", 1);
let limit = ctx.int_query_or("limit", 10);
let offset = (page - 1) * limit;
// In a real app, fetch from database
let posts = vec![
Post {
id: Some(1),
title: "First Post".to_string(),
content: "Content here".to_string(),
author: "Alice".to_string(),
published: true,
created_at: Some("2024-01-01T00:00:00Z".to_string()),
},
// ... more posts
];
ctx.json(json!({
"posts": posts,
"pagination": {
"page": page,
"limit": limit,
"total": posts.len(),
"total_pages": (posts.len() as f64 / limit as f64).ceil() as i32
}
}))
}
}
Get Single Post
#![allow(unused)]
fn main() {
async fn get_post(ctx: &mut Context) -> Result<()> {
let post_id = ctx.param_as::<i64>("id")?;
// In a real app, fetch from database
if post_id == 1 {
let post = Post {
id: Some(1),
title: "First Post".to_string(),
content: "Content here".to_string(),
author: "Alice".to_string(),
published: true,
created_at: Some("2024-01-01T00:00:00Z".to_string()),
};
ctx.json(json!({
"success": true,
"post": post
}))
} else {
ctx.throw404(Some("Post not found"))
}
}
}
Create Post
#![allow(unused)]
fn main() {
async fn create_post(ctx: &mut Context) -> Result<()> {
let request: CreatePostRequest = ctx.body_json()?;
// Validation
if request.title.trim().is_empty() {
return ctx.throw400(Some("Title is required"));
}
if request.content.trim().is_empty() {
return ctx.throw400(Some("Content is required"));
}
if request.author.trim().is_empty() {
return ctx.throw400(Some("Author is required"));
}
// In a real app, save to database
let post = Post {
id: Some(2), // Generated by database
title: request.title,
content: request.content,
author: request.author,
published: request.published.unwrap_or(false),
created_at: Some(chrono::Utc::now().to_rfc3339()),
};
ctx.status(hyper::StatusCode::CREATED);
ctx.json(json!({
"success": true,
"message": "Post created successfully",
"post": post
}))
}
}
Update Post
#![allow(unused)]
fn main() {
async fn update_post(ctx: &mut Context) -> Result<()> {
let post_id = ctx.param_as::<i64>("id")?;
let request: UpdatePostRequest = ctx.body_json()?;
// In a real app, fetch and update in database
if post_id == 1 {
let mut post = Post {
id: Some(1),
title: "First Post".to_string(),
content: "Content here".to_string(),
author: "Alice".to_string(),
published: true,
created_at: Some("2024-01-01T00:00:00Z".to_string()),
};
// Apply updates
if let Some(title) = request.title {
post.title = title;
}
if let Some(content) = request.content {
post.content = content;
}
if let Some(author) = request.author {
post.author = author;
}
if let Some(published) = request.published {
post.published = published;
}
ctx.json(json!({
"success": true,
"message": "Post updated successfully",
"post": post
}))
} else {
ctx.throw404(Some("Post not found"))
}
}
}
Delete Post
#![allow(unused)]
fn main() {
async fn delete_post(ctx: &mut Context) -> Result<()> {
let post_id = ctx.param_as::<i64>("id")?;
// In a real app, delete from database
if post_id == 1 {
ctx.json(json!({
"success": true,
"message": "Post deleted successfully",
"deleted_id": post_id
}))
} else {
ctx.throw404(Some("Post not found"))
}
}
}
Testing the API
Using curl
# List posts
curl http://localhost:8000/api/posts
# Get single post
curl http://localhost:8000/api/posts/1
# Create post
curl -X POST http://localhost:8000/api/posts \
-H "Content-Type: application/json" \
-d '{
"title": "New Post",
"content": "Post content",
"author": "Bob",
"published": true
}'
# Update post
curl -X PUT http://localhost:8000/api/posts/1 \
-H "Content-Type: application/json" \
-d '{
"title": "Updated Title"
}'
# Delete post
curl -X DELETE http://localhost:8000/api/posts/1
Error Handling
The API returns appropriate HTTP status codes:
200 OK- Success201 Created- Resource created400 Bad Request- Validation error404 Not Found- Resource not found500 Internal Server Error- Server error
Error responses follow this format:
{
"error": "Error message here"
}
Next Steps
- Add database integration - See Database Guide
- Add authentication - See Authentication Example
- Add middleware - See Middleware Guide
- Add input validation middleware
- Add rate limiting
- Add API versioning