RustAPI redefines API development for the AI era.
We combine Rust's performance and safety with FastAPI's ergonomics. Write type-safe, production-ready APIs without fighting trait bounds. MCP servers, LLM integrations, or classic REST APIs — one framework for all.
"API surface is ours, engines can change."
RustAPI follows a Facade Architecture — a stable, ergonomic public API that shields you from internal complexity and breaking changes.
| Principle | What It Means |
|---|---|
| 🎯 5-Line APIs | A working REST endpoint in 5 lines. No ceremony. |
| 🛡️ Stable Surface | Your code depends on rustapi-rs. Internal crates (hyper, tokio, validator) are implementation details. |
| 🔄 Engines Change | We can swap hyper for h3, upgrade tokio, or replace validator — your code stays the same. |
| 🎁 Batteries Included | JWT, CORS, Rate Limiting, OpenAPI — all built-in, all optional via feature flags. |
| 🤖 LLM-First | TOON format, token counting headers, MCP-ready. Built for the AI era. |
┌─────────────────────────────────────────────────────────────┐
│ Your Application │
│ use rustapi_rs::prelude::* │
├─────────────────────────────────────────────────────────────┤
│ rustapi-rs (Facade) │
│ Stable API ── Never Breaks │
├───────────────┬───────────────┬───────────────┬─────────────┤
│ rustapi-core │ rustapi-toon │ rustapi-extras│ ... │
│ (hyper) │ (serde) │ (jwt) │ │
├───────────────┴───────────────┴───────────────┴─────────────┤
│ Foundation: tokio, serde, hyper │
│ ↑ Can be upgraded/swapped internally │
└─────────────────────────────────────────────────────────────┘
Internal upgrades don't break your code. When hyper 2.0 releases, we update rustapi-core. Your RustApi::new() keeps working.
📚 Read more: docs/PHILOSOPHY.md | docs/ARCHITECTURE.md
use rustapi_rs::prelude::*;
#[rustapi_rs::get("/hello/{name}")]
async fn hello(Path(name): Path<String>) -> Json<Message> {
Json(Message { greeting: format!("Hello, {name}!") })
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
RustApi::auto().run("0.0.0.0:8080").await
}5 lines of code. Auto-generated OpenAPI docs. Production-ready.
RustAPI is blazingly fast — built on Tokio and Hyper 1.0, with zero-cost abstractions.
| Framework | Requests/sec | Latency (avg) | Memory |
|---|---|---|---|
| RustAPI | ~185,000 | ~0.54ms | ~8MB |
| Actix-web | ~178,000 | ~0.56ms | ~10MB |
| Axum | ~165,000 | ~0.61ms | ~12MB |
| Rocket | ~95,000 | ~1.05ms | ~15MB |
| FastAPI (Python) | ~12,000 | ~8.3ms | ~45MB |
🔬 Test Configuration
- Hardware: Intel i7-12700K, 32GB RAM
- Method:
wrk -t12 -c400 -d30s http://127.0.0.1:8080/api/users - Scenario: JSON serialization of 100 user objects
- Build:
cargo build --release
Results may vary based on hardware and workload. Run your own benchmarks:
cd benches
./run_benchmarks.ps1- ⚡ Zero-copy parsing — Direct memory access for path/query params
- 🔄 Async-first — Tokio runtime handles 100K+ concurrent connections
- 📦 Smart caching — Route matching cached via radix tree (matchit)
- 🎯 No dynamic dispatch — All extractors resolved at compile time
[dependencies]
rustapi-rs = "0.1.4"use rustapi_rs::prelude::*;
#[derive(Serialize, Schema)]
struct User { id: u64, name: String }
#[rustapi_rs::get("/users/{id}")]
async fn get_user(Path(id): Path<u64>) -> Json<User> {
Json(User { id, name: "Tunahan".into() })
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Zero config: all `#[rustapi_rs::get/post/..]` routes are auto-registered.
// Swagger UI is enabled at /docs by default (when built with the `swagger-ui` feature).
RustApi::auto().run("127.0.0.1:8080").await
}http://localhost:8080/docs → Swagger UI ready.
| Feature | Description |
|---|---|
| Type-Safe Extractors | Json<T>, Query<T>, Path<T>, WebSocket — compile-time guarantees |
| Zero-Config Routing | Macro-decorated routes auto-register at startup (RustApi::auto()) |
| Auto OpenAPI | Your code = your docs. /docs endpoint out of the box |
| Validation | #[validate(email)] → automatic 422 responses |
| JWT Auth | One-line auth with AuthUser<T> extractor |
| CORS & Rate Limit | Production-ready middleware |
| TOON Format | 50-58% token savings for LLMs |
| WebSocket | Real-time bidirectional communication with broadcast support |
| Template Engine | Server-side HTML rendering with Tera templates |
| CLI Tool | cargo-rustapi for project scaffolding |
rustapi-rs = { version = "0.1.4", features = ["jwt", "cors", "toon", "ws", "view"] }jwt— JWT authenticationcors— CORS middlewarerate-limit— IP-based rate limitingtoon— LLM-optimized responsesws— WebSocket supportview— Template engine (Tera)full— Everything included
All examples in this repository are written in the Phase 6 “zero-config” style.
cargo run -p hello-world # 5-line hello world
cargo run -p crud-api # Full CRUD with validation
cargo run -p auth-api # JWT authentication
cargo run -p sqlx-crud # Database integration (PostgreSQL)
cargo run -p toon-api # TOON format for LLMs
cargo run -p websocket # Real-time WebSocket chat
cargo run -p templates # Server-side rendering with Tera
cargo run -p mcp-server # Model Context Protocol server
cargo run -p rate-limit-demo # Rate limiting concepts
cargo run -p microservices # Service-to-service communication
cargo run -p middleware-chain # Middleware patterns
# cargo run -p graphql-api # GraphQL (coming soon)🌟 Getting Started
- hello-world — Minimal 5-line API
- crud-api — Complete CRUD with in-memory storage
- proof-of-concept — Feature showcase
🔐 Authentication & Security
- auth-api — JWT authentication & authorization
- rate-limit-demo — IP-based rate limiting
- middleware-chain — Custom auth middleware
🗄️ Database Integration
- sqlx-crud — PostgreSQL with SQLx
- database-pooling — Connection pool management
- redis-cache — Redis caching layer
🤖 AI & LLM
- toon-api — TOON format for token optimization
- mcp-server — Model Context Protocol integration
- llm-streaming — Streaming LLM responses
🌐 Real-time & Web
- websocket — WebSocket chat with broadcast
- templates — Server-side HTML rendering
- sse-events — Server-Sent Events
🏗️ Advanced Patterns
- graphql-api — GraphQL with async-graphql
- microservices — Multi-service architecture
- grpc-integration — gRPC + REST hybrid
RustAPI provides first-class WebSocket support for real-time applications.
use rustapi_rs::ws::{WebSocket, Message, Broadcast};
#[rustapi_rs::get("/ws")]
async fn websocket(ws: WebSocket) -> WebSocketUpgrade {
ws.on_upgrade(handle_connection)
}
async fn handle_connection(mut stream: WebSocketStream) {
while let Some(msg) = stream.recv().await {
match msg {
Message::Text(text) => {
stream.send(Message::Text(format!("Echo: {}", text))).await.ok();
}
Message::Close(_) => break,
_ => {}
}
}
}Features:
- Full WebSocket protocol support (text, binary, ping/pong)
Broadcastchannel for pub/sub patterns- Seamless integration with RustAPI routing
Server-side HTML rendering with Tera templates.
use rustapi_rs::view::{Templates, View, ContextBuilder};
#[rustapi_rs::get("/")]
async fn home(templates: Templates) -> View<()> {
View::new(&templates, "index.html", ())
}
#[rustapi_rs::get("/users/{id}")]
async fn user_page(templates: Templates, Path(id): Path<u64>) -> View<User> {
let user = get_user(id);
View::with_context(&templates, "user.html", user, |ctx| {
ctx.insert("title", &format!("User: {}", user.name));
})
}Features:
- Tera template engine (Jinja2-like syntax)
- Type-safe context with
ContextBuilder - Template inheritance support
- Auto-escape HTML by default
RustAPI is built for AI-powered APIs.
TOON (Token-Oriented Object Notation) uses 50-58% fewer tokens than JSON. Ideal for MCP servers, AI agents, and LLM integrations.
use rustapi_rs::toon::{Toon, LlmResponse, AcceptHeader};
// Direct TOON response
#[rustapi::get("/ai/users")]
async fn ai_users() -> Toon<UsersResponse> {
Toon(get_users())
}
// Content negotiation: JSON or TOON based on Accept header
#[rustapi::get("/users")]
async fn users(accept: AcceptHeader) -> LlmResponse<UsersResponse> {
LlmResponse::new(get_users(), accept.preferred)
}
// Headers: X-Token-Count-JSON, X-Token-Count-TOON, X-Token-SavingsWhy TOON?
- Compatible with Claude, GPT-4, Gemini — all major LLMs
- Cut your token costs in half
- Optimized for MCP (Model Context Protocol) servers
Scaffold new RustAPI projects with ease.
# Install the CLI
cargo install cargo-rustapi
# Create a new project
cargo rustapi new my-api
# Interactive mode
cargo rustapi new my-api --interactiveAvailable Templates:
minimal— Basic RustAPI setupapi— REST API with CRUD operationsweb— Full web app with templates and WebSocketfull— Everything included
Commands:
cargo rustapi new <name>— Create new projectcargo rustapi generate <type>— Generate handlers, models, middlewarecargo rustapi docs— Generate API documentation
RustAPI follows a Facade Architecture — a stable public API that shields you from internal changes.
graph TB
subgraph Client["🌐 Client Layer"]
HTTP[HTTP Request]
LLM[LLM/AI Agent]
MCP[MCP Client]
end
subgraph Public["📦 rustapi-rs (Public Facade)"]
direction TB
Prelude[prelude::*]
Macros["#[rustapi::get/post]<br>#[rustapi::main]"]
Types[Json, Query, Path, Form]
end
subgraph Core["⚙️ rustapi-core (Engine)"]
direction TB
Router[Radix Router<br>matchit]
Extract[Extractors<br>FromRequest trait]
MW[Middleware Stack<br>Tower-like layers]
Resp[Response Builder<br>IntoResponse trait]
end
subgraph Extensions["🔌 Extension Crates"]
direction LR
OpenAPI["rustapi-openapi<br>Swagger/Docs"]
Validate["rustapi-validate<br>Request Validation"]
Toon["rustapi-toon<br>LLM Optimization"]
Extras["rustapi-extras<br>JWT/CORS/RateLimit"]
WsCrate["rustapi-ws<br>WebSocket Support"]
ViewCrate["rustapi-view<br>Template Engine"]
end
subgraph Foundation["🏗️ Foundation Layer"]
direction LR
Tokio[tokio<br>Async Runtime]
Hyper[hyper 1.0<br>HTTP Protocol]
Serde[serde<br>Serialization]
end
HTTP --> Public
LLM --> Public
MCP --> Public
Public --> Core
Core --> Extensions
Extensions --> Foundation
Core --> Foundation
sequenceDiagram
participant C as Client
participant R as Router
participant M as Middleware
participant E as Extractors
participant H as Handler
participant S as Serializer
C->>R: HTTP Request
R->>R: Match route (radix tree)
R->>M: Pass to middleware stack
loop Each Middleware
M->>M: Process (JWT, CORS, RateLimit)
end
M->>E: Extract parameters
E->>E: Json<T>, Path<T>, Query<T>
E->>E: Validate with #[validate]
alt Validation Failed
E-->>C: 422 Unprocessable Entity
else Validation OK
E->>H: Call async handler
H->>S: Return response type
alt TOON Enabled
S->>S: Check Accept header
S->>S: Serialize as TOON/JSON
S->>S: Add token count headers
else Standard
S->>S: Serialize as JSON
end
S-->>C: HTTP Response
end
graph BT
subgraph User["Your Application"]
App[main.rs]
end
subgraph Facade["Single Import"]
RS[rustapi-rs]
end
subgraph Internal["Internal Crates"]
Core[rustapi-core]
Macros[rustapi-macros]
OpenAPI[rustapi-openapi]
Validate[rustapi-validate]
Toon[rustapi-toon]
Extras[rustapi-extras]
WS[rustapi-ws]
View[rustapi-view]
end
subgraph External["External Dependencies"]
Tokio[tokio]
Hyper[hyper]
Serde[serde]
Utoipa[utoipa]
Validator[validator]
Tungstenite[tungstenite]
Tera[tera]
end
App --> RS
RS --> Core
RS --> Macros
RS --> OpenAPI
RS --> Validate
RS -.->|optional| Toon
RS -.->|optional| Extras
RS -.->|optional| WS
RS -.->|optional| View
Core --> Tokio
Core --> Hyper
Core --> Serde
OpenAPI --> Utoipa
Validate --> Validator
Toon --> Serde
WS --> Tungstenite
View --> Tera
style RS fill:#e1f5fe
style App fill:#c8e6c9
| Principle | Implementation |
|---|---|
| Single Entry Point | use rustapi_rs::prelude::* imports everything you need |
| Zero Boilerplate | Macros generate routing, OpenAPI specs, and validation |
| Compile-Time Safety | Generic extractors catch type errors at compile time |
| Opt-in Complexity | Features like JWT, TOON are behind feature flags |
| Engine Abstraction | Internal hyper/tokio upgrades don't break your code |
| Crate | Role |
|---|---|
rustapi-rs |
Public facade — single use for everything |
rustapi-core |
HTTP engine, routing, extractors, response handling |
rustapi-macros |
Procedural macros: #[rustapi::get], #[rustapi::main] |
rustapi-openapi |
Swagger UI generation, OpenAPI 3.0 spec |
rustapi-validate |
Request body/query validation via #[validate] |
rustapi-toon |
TOON format serializer, content negotiation, LLM headers |
rustapi-extras |
JWT auth, CORS, rate limiting middleware |
rustapi-ws |
WebSocket support with broadcast channels |
rustapi-view |
Template engine (Tera) for server-side rendering |
- Core framework (routing, extractors, server)
- OpenAPI & Validation
- JWT, CORS, Rate Limiting
- TOON format & LLM optimization
- WebSocket support
- Template engine (Tera)
- CLI tool (cargo-rustapi)
- GraphQL support (via async-graphql)
- gRPC integration (Tonic compatibility)
- Distributed tracing (OpenTelemetry)
- Server-Sent Events (SSE)
- File upload/download (multipart forms)
- Caching layers (Redis, in-memory)
- Background jobs (Tokio tasks, queues)
- Health checks (liveness/readiness probes)
- Metrics (Prometheus exporters)
- HTTP/3 & QUIC support
- 🤖 AI/LLM APIs — MCP servers, token-optimized responses
- 🚀 Startups — Rapid prototyping with production-ready code
- 🏢 Microservices — Service-to-service communication
- 📱 Mobile Backends — Fast, type-safe REST APIs
- 🔄 Real-time Apps — WebSocket support built-in
- 📊 Data Platforms — High-performance data ingestion
Building something with RustAPI? Add your project!
| Feature | RustAPI | Axum | Actix-web | Rocket | FastAPI (Python) |
|---|---|---|---|---|---|
| Performance | ⚡⚡⚡⚡⚡ | ⚡⚡⚡⚡ | ⚡⚡⚡⚡⚡ | ⚡⚡⚡ | ⚡ |
| Learning Curve | 📚📚 | 📚📚📚 | 📚📚📚📚 | 📚📚 | 📚 |
| Auto OpenAPI | ✅ Built-in | ✅ Limited | ✅ Built-in | ||
| Validation | ✅ Automatic | ✅ Basic | ✅ Pydantic | ||
| JWT Auth | ✅ Built-in | ❌ | |||
| WebSocket | ✅ Built-in | ✅ Built-in | ✅ Built-in | ❌ | ✅ Built-in |
| LLM/TOON | ✅ Unique | ❌ | ❌ | ❌ | ❌ |
| Zero Config | ✅ auto() |
✅ Auto | |||
| Stability | ✅ Facade | ✅ Stable | |||
| Async/Await | ✅ Native | ✅ Native | ✅ Native | ✅ Native |
- 🎯 5-Line APIs — Fastest time-to-production
- 🛡️ Facade Pattern — Internal upgrades don't break your code
- 🤖 AI-Ready — TOON format, MCP servers, LLM optimization
- 🎁 Batteries Included — JWT, CORS, Rate Limiting, OpenAPI — all built-in
- 📚 Better DX — FastAPI's ergonomics in Rust
We welcome contributions! Here's how you can help:
- ⭐ Star this repo — Helps others discover RustAPI
- 🐛 Report bugs — Open an issue with reproduction steps
- 💡 Suggest features — Share your ideas in Discussions
- 📝 Improve docs — Fix typos, add examples
- 🔧 Submit PRs — See CONTRIBUTING.md
# Clone the repo
git clone https://github.com/Tuntii/RustAPI.git
cd RustAPI
# Run tests
cargo test --all
# Run benchmarks
cd benches && ./run_benchmarks.ps1
# Check formatting
cargo fmt --check
# Run clippy
cargo clippy --all-targets --all-features- 📖 Documentation: docs.rs/rustapi-rs
- 💬 Discussions: GitHub Discussions
- 🐦 Twitter: @Tuntii
- 🌐 Website: tunti35.com/projects/rustapi
- 📧 Email: [email protected]
If you find RustAPI useful, please consider giving it a star! It helps others discover the project.
MIT or Apache-2.0, at your option.
