Skip to content

Production-ready RustAPI framework examples: REST APIs, GraphQL, microservices, JWT auth, real-time WebSockets, TOON format, MCP servers, and serverless. Complete with learning paths and comprehensive documentation.

Notifications You must be signed in to change notification settings

Tuntii/RustAPI-examples

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

RustAPI Examples

Rust RustAPI License Cookbook

Production-ready examples demonstrating the full power of RustAPI β€” the Rust web framework with FastAPI-like developer experience.

πŸ“š Official Resources:


πŸš€ Why RustAPI?

"Rust Speed. Python Simplicity. AI Efficiency."

Metric RustAPI Actix Axum FastAPI (Python)
Performance ~92k req/s ~105k ~100k ~12k
Developer Experience 🟒 High πŸ”΄ Low 🟑 Medium 🟒 High
Boilerplate Zero High Medium Zero
AI/LLM Native βœ… ❌ ❌ ❌
Type Safety βœ… βœ… βœ… ❌

Key Features

  • 🎯 Zero Boilerplate β€” RustApi::auto() discovers all routes automatically
  • πŸ“ Auto Documentation β€” OpenAPI/Swagger at /docs out of the box
  • βœ… Built-in Validation β€” #[validate] with detailed error messages
  • πŸ” JWT Authentication β€” First-class JwtLayer and AuthUser<T> extractor
  • πŸ€– AI-First Architecture β€” TOON format (50-58% token savings), MCP support
  • ⚑ Middleware Stack β€” Rate limiting, CORS, logging, circuit breaker, and more
  • 🌐 Real-time β€” WebSocket support with broadcast channels

πŸ“‹ Prerequisites

Before running these examples, ensure you have:

# Rust 1.70 or later
rustc --version

# Clone the examples repository
git clone https://github.com/Tuntii/rustapi-rs-examples.git
cd rustapi-rs-examples

# Build all examples
cargo build --release

Optional dependencies (for specific examples):

  • Docker β€” For sqlx-crud (PostgreSQL/SQLite)
  • SQLite β€” For sqlx-crud local testing

πŸ“‚ Examples Overview

This repository contains 18 production-ready examples organized by category:

🌟 Getting Started

Example Difficulty Description Key Features
hello-world ⭐ Minimal 20-line API RustApi::auto(), path params, Json response
crud-api ⭐⭐ Complete CRUD operations Validation, pagination, error handling, body limits
proof-of-concept ⭐⭐⭐ Full-featured bookmark manager JWT, CRUD, SSE, modular handlers, Swagger UI

πŸ” Authentication & Security

Example Difficulty Description Key Features
auth-api ⭐⭐⭐ JWT authentication system Login/register, JwtLayer, AuthUser<T>, protected routes
rate-limit-demo ⭐⭐ IP-based rate limiting Per-endpoint limits, burst support, 429 handling
middleware-chain ⭐⭐⭐ Custom middleware composition Request ID, timing, auth, middleware ordering
cors-test ⭐⭐ CORS configuration CorsLayer, allowed origins/methods/headers

πŸ—„οΈ Database Integration

Example Difficulty Description Key Features
sqlx-crud ⭐⭐⭐ SQLx + SQLite/PostgreSQL Connection pooling, transactions, migrations
event-sourcing ⭐⭐⭐⭐ Event sourcing pattern CQRS, domain events, aggregate reconstruction

πŸ€– AI & LLM Integration

Example Difficulty Description Key Features
toon-api ⭐⭐ Token-optimized responses ToonResponse, content negotiation, token headers
mcp-server ⭐⭐⭐ Model Context Protocol Tool definitions, resource management, AI agents

🌐 Real-time & Web

Example Difficulty Description Key Features
websocket ⭐⭐⭐ WebSocket chat server Broadcast channels, pub/sub, connection management
templates ⭐⭐ Server-side rendering Tera templates, inheritance, static files

πŸ—οΈ Advanced Architecture

Example Difficulty Description Key Features
graphql-api ⭐⭐⭐⭐ GraphQL integration async-graphql, queries/mutations, playground
microservices ⭐⭐⭐⭐ API Gateway pattern Service-to-service communication, routing
microservices-advanced ⭐⭐⭐⭐ Service discovery Registry, heartbeat, Docker Compose
phase11-demo ⭐⭐⭐⭐ Advanced middleware Guards, circuit breaker, timeout, logging
serverless-lambda ⭐⭐⭐ AWS Lambda deployment SAM template, cold start optimization

⚠️ Note: serverless-lambda uses AWS Lambda HTTP runtime instead of RustAPI for serverless deployment patterns.


🎯 Feature Coverage Matrix

Feature Examples Using It
RustApi::auto() All examples
Json<T> / JsonResponse crud-api, auth-api, proof-of-concept, graphql-api
#[validate] crud-api, auth-api, proof-of-concept
JwtLayer / AuthUser<T> auth-api, middleware-chain, phase11-demo, proof-of-concept
RateLimitLayer rate-limit-demo, auth-api, cors-test, proof-of-concept
CorsLayer cors-test, middleware-chain, proof-of-concept
ToonResponse toon-api, mcp-server
WebSocket / WsConnection websocket
View<T> / ViewEngine templates
State<T> All examples with shared state
RequestIdLayer middleware-chain, phase11-demo
CircuitBreakerLayer phase11-demo
TimeoutLayer phase11-demo

πŸ“Š RustAPI Feature Flags

Each example uses specific Cargo feature flags. See FEATURES.md for detailed documentation.

Feature Flag Purpose Examples
full All features enabled crud-api, phase11-demo
jwt JWT authentication auth-api, middleware-chain, proof-of-concept
cors CORS middleware cors-test, middleware-chain, proof-of-concept
rate-limit Rate limiting rate-limit-demo, auth-api, cors-test, proof-of-concept
toon TOON format for LLMs toon-api, mcp-server
ws WebSocket support websocket
view Template rendering templates
swagger-ui Swagger UI at /docs toon-api

πŸš€ Quick Start

Running an Example

# Navigate to repository
cd rustapi-rs-examples

# Run any example
cargo run -p hello-world

# Run with debug logging
RUST_LOG=debug cargo run -p crud-api

# Access Swagger documentation (when running)
# http://127.0.0.1:8080/docs

Testing API Endpoints

# Hello World
curl http://127.0.0.1:8080/
curl http://127.0.0.1:8080/hello/RustAPI

# CRUD API
curl http://127.0.0.1:8080/users
curl -X POST http://127.0.0.1:8080/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice", "email": "alice@example.com"}'

# Auth API
curl -X POST http://127.0.0.1:8080/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "password"}'

πŸ“š Learning Path

For a structured learning experience, follow our recommended progression in LEARNING_PATH.md:

1. hello-world     β†’ Basic routing, responses
2. crud-api        β†’ Validation, error handling, state management
3. auth-api        β†’ JWT authentication, protected routes
4. middleware-chain β†’ Custom middleware, composition
5. proof-of-concept β†’ Full application architecture

πŸ”— Cookbook Cross-References

Each example maps to sections in the RustAPI Cookbook:

Example Cookbook Section
hello-world Getting Started β†’ Quickstart
crud-api Recipes β†’ CRUD Resources
auth-api Recipes β†’ JWT Authentication
middleware-chain Recipes β†’ Custom Middleware
sqlx-crud Recipes β†’ Database Integration
websocket Recipes β†’ WebSockets
templates Crates β†’ rustapi-view
toon-api Crates β†’ rustapi-toon

πŸ“ Creating Your Own Example

  1. Create directory: my-example/

  2. Add Cargo.toml:

    [package]
    name = "my-example"
    version = "0.1.0"
    edition = "2021"
    
    [dependencies]
    rustapi-rs = { path = "../../crates/rustapi-rs", features = ["full"] }
    tokio = { version = "1", features = ["full"] }
    serde = { version = "1", features = ["derive"] }
  3. Create src/main.rs:

    use rustapi_rs::prelude::*;
    
    #[rustapi_rs::get("/")]
    async fn index() -> &'static str {
        "Hello from my example!"
    }
    
    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        RustApi::auto().run("127.0.0.1:8080").await
    }
  4. Run it:

    cargo run -p my-example

🎯 Roadmap

Coming Soon

  • redis-cache β€” Redis caching layer
  • sse-events β€” Server-Sent Events streaming
  • grpc-integration β€” gRPC + REST hybrid API
  • distributed-tracing β€” OpenTelemetry integration
  • kubernetes-ready β€” Health checks, metrics, graceful shutdown

🀝 Contributing

Contributions are welcome! See our Contributing Guide for details.

  1. Fork this repository
  2. Create your example in a new directory
  3. Add comprehensive documentation (README.md)
  4. Submit a pull request

πŸ“„ License

This project is licensed under the MIT OR Apache-2.0 license, same as RustAPI.


Built with ❀️ using RustAPI

Framework Β· Cookbook Β· Examples Β· Discussions

About

Production-ready RustAPI framework examples: REST APIs, GraphQL, microservices, JWT auth, real-time WebSockets, TOON format, MCP servers, and serverless. Complete with learning paths and comprehensive documentation.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published