Expand description
Ultra-optimized Rust web framework inspired by FastAPI.
fastapi_rust provides a type-safe, high-performance web framework with:
- Type-driven API design — Route handlers declare types, framework extracts/validates automatically
- Dependency injection — Composable, testable request handling
- Automatic OpenAPI — Schema generation from type definitions
- First-class async — Built on asupersync for structured concurrency
- Dependency discipline — No Tokio/Hyper/Tower/Axum; direct deps kept small
§Role In The System
fastapi_rust is the user-facing facade crate. It re-exports the framework’s
core types, macros, and utilities from the sub-crates so applications only
need a single dependency. All real behavior lives in the sub-crates listed
below; this crate exists to provide a cohesive, ergonomic API surface.
§Quick Start
use fastapi_rust::prelude::*;
#[derive(Serialize, Deserialize, JsonSchema)]
struct Item {
id: i64,
name: String,
}
#[get("/items/{id}")]
async fn get_item(cx: &Cx, id: Path<i64>) -> Json<Item> {
Json(Item { id: id.0, name: "Example".into() })
}
fn main() {
let app = App::builder()
.title("My API")
.route_entry(get_item_route())
.build();
let rt = asupersync::runtime::RuntimeBuilder::current_thread()
.build()
.expect("runtime must build");
rt.block_on(async move {
serve(app, "0.0.0.0:8000").await.expect("server must start");
});
}§Design Philosophy
This framework is built with the following principles:
- Zero-cost abstractions — No runtime reflection, everything at compile time
- Cancel-correct — Leverages asupersync’s structured concurrency
- Minimal allocations — Zero-copy parsing where possible
- Familiar API — FastAPI users will recognize the patterns
§Crate Structure
| Crate | Purpose |
|---|---|
fastapi_core | Core types (Request, Response, Error), extractors, middleware, DI |
fastapi_http | Zero-copy HTTP/1.1 parser, TCP server, chunked encoding |
fastapi_router | Trie-based router with O(log n) lookups |
fastapi_macros | Procedural macros (#[get], #[derive(Validate)], #[derive(JsonSchema)]) |
fastapi_openapi | OpenAPI 3.1 schema types and generation |
fastapi_output | Agent-aware rich console output (optional) |
§Feature Flags
| Feature | Default | Description |
|---|---|---|
output | yes | Rich console output with agent detection (includes fastapi-output/rich) |
output-plain | no | Plain-text-only output (smaller binary, no ANSI codes) |
full | no | All output features including every theme and component |
§Sub-crate Feature Flags
fastapi-core:
| Feature | Description |
|---|---|
regex | Regex support in testing assertions |
compression | Response compression middleware (gzip via flate2) |
proptest | Property-based testing support |
§Cookbook
Common patterns for building APIs with fastapi_rust.
§JSON CRUD Handler
use fastapi_rust::prelude::*;
#[get("/items/{id}")]
async fn get_item(cx: &Cx, id: Path<i64>, state: State<AppState>) -> Result<Json<Item>, HttpError> {
let item = state.db.find(id.0).await?;
Ok(Json(item))
}§Pagination
use fastapi_rust::prelude::*;
#[get("/items")]
async fn list_items(cx: &Cx, page: Pagination) -> Json<Page<Item>> {
// page.page() returns current page (default: 1)
// page.per_page() returns items per page (default: 20, max: 100)
let items = db.list(page.offset(), page.limit()).await;
Json(Page::new(items, total_count, page.page(), page.per_page()))
}§Bearer Token Authentication
use fastapi_rust::prelude::*;
#[get("/protected")]
async fn protected(cx: &Cx, token: BearerToken) -> Json<UserInfo> {
let user = verify_jwt(token.token()).await?;
Json(user)
}§Background Tasks
use fastapi_rust::prelude::*;
#[post("/send-email")]
async fn send_email(cx: &Cx, body: Json<EmailRequest>, tasks: BackgroundTasks) -> StatusCode {
tasks.add(move || {
// Runs after response is sent
email_service::send(&body.to, &body.subject, &body.body);
});
StatusCode::ACCEPTED
}§CORS + Rate Limiting Middleware
use fastapi_rust::prelude::*;
let app = App::new()
.middleware(Cors::new().allow_any_origin(true).allow_credentials(true))
.middleware(RateLimitBuilder::new().max_requests(100).window_secs(60).build());§Error Handling
use fastapi_rust::prelude::*;
// Custom errors implement IntoResponse automatically via HttpError
fn not_found(resource: &str, id: u64) -> HttpError {
HttpError::not_found(format!("{} {} not found", resource, id))
}§Migrating from Python FastAPI
§Key Differences
| Python FastAPI | fastapi_rust | Notes |
|---|---|---|
@app.get("/") | #[get("/")] | Proc macro instead of decorator |
async def handler(item: Item) | async fn handler(cx: &Cx, item: Json<Item>) | Explicit Cx context + typed extractors |
Depends(get_db) | Depends<DbPool> | Type-based DI, not function-based |
HTTPException(404) | HttpError::not_found(msg) | Typed error constructors |
BackgroundTasks | BackgroundTasks | Same concept, different API |
Query(q: str) | Query<SearchParams> | Struct-based query extraction |
Path(item_id: int) | Path<i64> | Type-safe path parameters |
Body(...) | Json<T> | Explicit JSON extraction |
Response(status_code=201) | StatusCode::CREATED | Type-safe status codes |
§Async Runtime
Python FastAPI uses asyncio. fastapi_rust uses asupersync, which provides:
- Structured concurrency: Request handlers run in regions
- Cancel-correctness: Graceful cancellation via checkpoints
- Budgeted timeouts: Request timeouts via budget exhaustion
Every handler receives &Cx as its first parameter for async context.
§Dependency Injection
Python uses function-based DI with Depends(func). Rust uses trait-based DI:
// Python:
// async def get_db():
// yield db_session
//
// @app.get("/")
// async def handler(db: Session = Depends(get_db)):
// Rust:
impl FromDependency for DbPool {
async fn from_dependency(cx: &Cx, cache: &DependencyCache) -> Result<Self, HttpError> {
Ok(DbPool::acquire(cx).await?)
}
}
#[get("/")]
async fn handler(cx: &Cx, db: Depends<DbPool>) -> Json<Data> { ... }§Validation
Python uses Pydantic models. Rust uses #[derive(Validate)]:
// Python:
// class Item(BaseModel):
// name: str = Field(..., min_length=1, max_length=100)
// price: float = Field(..., gt=0)
// Rust:
#[derive(Validate)]
struct Item {
#[validate(min_length = 1, max_length = 100)]
name: String,
#[validate(range(min = 0.01))]
price: f64,
}Re-exports§
pub use fastapi_core as core;pub use fastapi_http as http;pub use fastapi_macros as macros;pub use fastapi_openapi as openapi;pub use fastapi_router as router;
Modules§
- extract
- Extractors module for request data extraction (extended).
- extractors
- Extractors module for type-safe request data extraction.
- prelude
- Prelude module for convenient imports.
- server
- HTTP server module with server types and configuration.
- testing
- Testing utilities module.
Structs§
- Accept
- Accept header marker.
- AddResponse
Header - Middleware that adds a custom header to all responses.
- Allowed
Methods - Allowed methods for a matched path.
- App
- A configured web application.
- AppBuilder
- Builder for constructing an
App. - AppConfig
- Application configuration.
- AppState
- Application state container.
- Authorization
- Authorization header marker.
- Background
Tasks - Basic
Auth - HTTP Basic Authentication credentials extractor.
- Basic
Auth Error - Error when HTTP Basic Auth extraction fails.
- Bearer
Token - Bearer token extractor for
Authorization: Bearer <token>. - Bearer
Token Error - Error when bearer token extraction fails.
- Content
Type - Content-Type header marker.
- Cookie
- Cookie value extractor.
- Cookie
Jar - A simple cookie jar for maintaining cookies across requests.
- Cors
- CORS middleware.
- Cors
Config - Cross-Origin Resource Sharing (CORS) configuration.
- Cx
- The capability context for a task.
- Default
Dependency Config - Default dependency configuration (cache per request).
- Dependency
Overrides - Dependency override registry (primarily for testing).
- Depends
- Dependency injection extractor.
- Header
- Header extractor for individual HTTP headers.
- Header
Values - Multiple header values extractor.
- Host
- Host header marker.
- Http
Error - HTTP error that produces a response.
- Invalid
Route Error - Error returned when a route path is invalid.
- Json
- JSON body extractor.
- Json
Config - Configuration for JSON extraction.
- Named
Header - Named header extractor with explicit header name.
- NoCache
- Disable caching for this dependency.
- OAuth2
Bearer Error - Error when OAuth2 bearer token extraction fails.
- OAuth2
Password Bearer - OAuth2 password bearer security scheme extractor.
- OAuth2
Password Bearer Config - Configuration for OAuth2PasswordBearer extraction.
- OpenApi
- OpenAPI 3.1 document.
- Open
ApiBuilder - OpenAPI document builder.
- Page
- Generic paginated response payload.
- Pagination
- Pagination extractor: reads
?page=and?per_page=from the query string. - Pagination
Config - Pagination extractor configuration.
- Param
Info - Path parameter information with optional OpenAPI metadata.
- Path
- Path parameter extractor.
- Path
Params - Extracted path parameters stored in request extensions.
- Query
- Query string extractor.
- Query
Params - Stored query parameters for extraction.
- Request
- HTTP request.
- Request
Builder - Builder for constructing test requests with a fluent API.
- Request
Context - Request context that wraps asupersync’s capability context.
- Request
Id - A request ID that was extracted or generated for the current request.
- Request
IdConfig - Configuration for request ID middleware.
- Request
IdMiddleware - Middleware that adds unique request IDs to requests and responses.
- Response
- HTTP response.
- Route
- A route definition used for routing and (optionally) metadata.
- Route
Conflict Error - Error returned when a new route conflicts with an existing one.
- Route
Match - A matched route with extracted parameters.
- Router
- Radix trie router.
- Schema
Registry - Schema registry for
#/components/schemas. - Server
- Synchronous HTTP server for request/response conversion.
- Server
Config - Server configuration for the HTTP/1.1 server.
- Shutdown
Controller - Controller for coordinated graceful shutdown.
- Shutdown
Receiver - Receiver for shutdown notifications.
- State
- State extractor for application-wide shared state.
- State
Container - Type-safe application state container.
- Status
Code - HTTP status code.
- TcpServer
- TCP server with asupersync integration.
- Test
Client - Test client for in-process HTTP testing.
- Test
Response - Response from a test request with assertion helpers.
- User
Agent - User-Agent header marker.
- Validation
Error - A single validation error item.
- Validation
Errors - Collection of validation errors (422 Unprocessable Entity response).
- XRequest
Id - X-Request-Id header marker.
Enums§
- Conversion
Error - Error type for parameter conversion failures.
- Converter
- Path parameter type converter.
- Dependency
Scope - Dependency resolution scope.
- Graceful
Outcome - Outcome of a task run with graceful shutdown support.
- Header
Extract Error - Error returned when header extraction fails.
- Json
Extract Error - Error returned when JSON extraction fails.
- Method
- HTTP method.
- Param
Value - A type-converted path parameter value.
- Path
Extract Error - Error returned when path extraction fails.
- Query
Extract Error - Error type for query string extraction failures.
- Response
Body - Response body.
- Route
AddError - Error returned when adding a route fails.
- Route
Lookup - Result of attempting to locate a route by path and method.
- Same
Site - SameSite cookie attribute.
- Serve
Error - Error returned when starting or running the server fails.
- Server
Error - HTTP server error.
Constants§
- DEFAULT_
PAGE - Default page number used when
pageis not provided. - DEFAULT_
PER_ PAGE - Default items-per-page used when
per_pageis not provided. - MAX_
PER_ PAGE - Maximum allowed
per_pagevalue.
Traits§
- Depends
Config - Configuration for
Dependsresolution. - From
Dependency - Trait for types that can be injected as dependencies.
- From
Request - Trait for types that can be extracted from a request.
- Into
Response - Trait for types that can be converted into a response.
- Open
ApiExt - Extension trait for generating OpenAPI specifications from applications.
Functions§
- serve
- Convenience function to serve an App on the given address.
- serve_
with_ config - Convenience function to serve an App with custom configuration.
Type Aliases§
- Default
Config - Backwards-friendly alias for the default config.
Attribute Macros§
- delete
- Mark a function as a DELETE handler.
- get
- Mark a function as a GET handler.
- head
- Mark a function as a HEAD handler.
- options
- Mark a function as an OPTIONS handler.
- patch
- Mark a function as a PATCH handler.
- post
- Mark a function as a POST handler.
- put
- Mark a function as a PUT handler.
Derive Macros§
- Json
Schema - Derive JSON Schema for OpenAPI.
- Validate
- Derive validation for a struct.