Skip to main content

Crate fastapi_rust

Crate fastapi_rust 

Source
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
  • Minimal dependencies — Only asupersync + serde

§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::new()
        .title("My API")
        .route(get_item);

    // Run with asupersync
    // asupersync::block_on(app.serve("0.0.0.0:8000"));
}

§Design Philosophy

This framework is built with the following principles:

  1. Zero-cost abstractions — No runtime reflection, everything at compile time
  2. Cancel-correct — Leverages asupersync’s structured concurrency
  3. Minimal allocations — Zero-copy parsing where possible
  4. Familiar API — FastAPI users will recognize the patterns

§Crate Structure

CratePurpose
fastapi_coreCore types (Request, Response, Error), extractors, middleware, DI
fastapi_httpZero-copy HTTP/1.1 parser, TCP server, chunked encoding
fastapi_routerTrie-based router with O(log n) lookups
fastapi_macrosProcedural macros (#[get], #[derive(Validate)], #[derive(JsonSchema)])
fastapi_openapiOpenAPI 3.1 schema types and generation
fastapi_outputAgent-aware rich console output (optional)

§Feature Flags

FeatureDefaultDescription
outputyesRich console output with agent detection (includes fastapi-output/rich)
output-plainnoPlain-text-only output (smaller binary, no ANSI codes)
fullnoAll output features including every theme and component

§Sub-crate Feature Flags

fastapi-core:

FeatureDescription
regexRegex support in testing assertions
compressionResponse compression middleware (gzip via flate2)
proptestProperty-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 FastAPIfastapi_rustNotes
@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
BackgroundTasksBackgroundTasksSame 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::CREATEDType-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§

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.
AddResponseHeader
Middleware that adds a custom header to all responses.
AllowedMethods
Allowed methods for a matched path.
App
A configured web application.
AppBuilder
Builder for constructing an App.
AppConfig
Application configuration for the FastAPI Rust framework.
AppState
Application state container.
Authorization
Authorization header marker.
BackgroundTasks
Background task queue for running tasks after response is sent.
BackgroundTasksInner
Internal storage for background tasks (thread-safe).
BasicAuth
Extracts HTTP Basic authentication credentials from the Authorization header.
BearerToken
Simple HTTP bearer token extractor.
ContentType
Content-Type header marker.
Cookie
A cookie to set in the response.
CookieJar
A simple cookie jar for maintaining cookies across requests.
Cors
CORS middleware.
CorsConfig
Cross-Origin Resource Sharing (CORS) configuration.
DefaultDependencyConfig
Default dependency configuration (cache per request).
DependencyOverrides
Dependency override registry (primarily for testing).
Depends
Dependency injection extractor.
Header
Header extractor for individual HTTP headers.
HeaderValues
Multiple header values extractor.
Host
Host header marker.
HttpError
HTTP error that produces a response.
InvalidRouteError
Error returned when a route path is invalid.
Json
JSON body extractor.
JsonConfig
Configuration for JSON request body extraction.
NamedHeader
Named header extractor with explicit header name.
NoCache
Disable caching for this dependency.
OAuth2BearerError
Error when OAuth2 bearer token extraction fails.
OAuth2PasswordBearer
OAuth2 password bearer security scheme extractor.
OAuth2PasswordBearerConfig
Configuration for OAuth2PasswordBearer extraction.
OpenApi
OpenAPI 3.1 document.
OpenApiBuilder
OpenAPI document builder.
Page
Paginated response wrapper.
Pagination
Pagination query parameters extractor.
PaginationConfig
Configuration for pagination behavior.
ParamInfo
Path parameter information with optional OpenAPI metadata.
Path
Path parameter extractor.
PathParams
Extracted path parameters stored in request extensions.
Query
Query string extractor.
QueryParams
Stored query parameters for extraction.
Request
HTTP request.
RequestBuilder
Builder for constructing test requests with a fluent API.
RequestContext
Request context that wraps asupersync’s capability context.
RequestCookies
Extract all cookies from the incoming request as a map.
RequestId
A request ID that was extracted or generated for the current request.
RequestIdConfig
Configuration for request ID middleware.
RequestIdMiddleware
Middleware that adds unique request IDs to requests and responses.
RequestRef
Read-only request data access.
Response
HTTP response.
ResponseMut
Mutable response wrapper for setting headers and cookies.
ResponseMutations
Mutable response container for setting response headers and cookies.
Route
A route definition with handler for request processing.
RouteConflictError
Error returned when a new route conflicts with an existing one.
RouteMatch
A matched route with extracted parameters.
Router
Radix trie router.
SchemaRegistry
Registry for collecting and deduplicating JSON schemas.
Server
Synchronous HTTP server for request/response conversion.
ServerConfig
Server configuration for the HTTP/1.1 server.
ShutdownController
Controller for coordinated graceful shutdown.
ShutdownReceiver
Receiver for shutdown notifications.
State
State extractor for application-wide shared state.
StateContainer
Type-safe application state container.
StatusCode
HTTP status code.
TcpServer
TCP server with asupersync integration.
TestClient
Test client for in-process HTTP testing.
TestResponse
Response from a test request with assertion helpers.
UserAgent
User-Agent header marker.
ValidationError
A single validation error item.
ValidationErrors
Collection of validation errors (422 Unprocessable Entity response).
XRequestId
X-Request-Id header marker.

Enums§

BasicAuthError
Error when basic auth extraction fails.
BearerTokenError
Error when bearer token extraction fails.
ConfigError
Configuration loading errors.
ConversionError
Error type for parameter conversion failures.
Converter
Path parameter type converter.
CookiePrefix
Cookie security prefix types.
CookiePrefixError
Errors that can occur when validating cookie prefixes.
DependencyScope
Dependency resolution scope.
GracefulOutcome
Outcome of a task run with graceful shutdown support.
HeaderExtractError
Error returned when header extraction fails.
JsonExtractError
Error returned when JSON extraction fails.
Method
HTTP method.
ParamValue
A type-converted path parameter value.
PathExtractError
Error returned when path extraction fails.
QueryExtractError
Error type for query string extraction failures.
ResponseBody
Response body.
RouteAddError
Error returned when adding a route fails.
RouteLookup
Result of attempting to locate a route by path and method.
SameSite
SameSite cookie attribute.
ServeError
Error returned when starting or running the server fails.
ServerError
HTTP server error.

Constants§

DEFAULT_PAGE
Default page number (1-indexed).
DEFAULT_PER_PAGE
Default items per page.
MAX_PER_PAGE
Maximum items per page (to prevent abuse).

Traits§

DependsConfig
Configuration for Depends resolution.
FromDependency
Trait for types that can be injected as dependencies.
FromRequest
Trait for types that can be extracted from a request.
IntoResponse
Trait for types that can be converted into a response.

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§

DefaultConfig
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§

JsonSchema
Derive JSON Schema for OpenAPI.
Validate
Derive validation for a struct.