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
  • 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:

  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§

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.
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.
AppState
Application state container.
Authorization
Authorization header marker.
BackgroundTasks
BasicAuth
HTTP Basic Authentication credentials extractor.
BasicAuthError
Error when HTTP Basic Auth extraction fails.
BearerToken
Bearer token extractor for Authorization: Bearer <token>.
BearerTokenError
Error when bearer token extraction fails.
ContentType
Content-Type header marker.
Cookie
Cookie value extractor.
CookieJar
A simple cookie jar for maintaining cookies across requests.
Cors
CORS middleware.
CorsConfig
Cross-Origin Resource Sharing (CORS) configuration.
Cx
The capability context for a task.
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 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
Generic paginated response payload.
Pagination
Pagination extractor: reads ?page= and ?per_page= from the query string.
PaginationConfig
Pagination extractor configuration.
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.
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.
Response
HTTP response.
Route
A route definition used for routing and (optionally) metadata.
RouteConflictError
Error returned when a new route conflicts with an existing one.
RouteMatch
A matched route with extracted parameters.
Router
Radix trie router.
SchemaRegistry
Schema registry for #/components/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§

ConversionError
Error type for parameter conversion failures.
Converter
Path parameter type converter.
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 used when page is not provided.
DEFAULT_PER_PAGE
Default items-per-page used when per_page is not provided.
MAX_PER_PAGE
Maximum allowed per_page value.

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.
OpenApiExt
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§

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.