Skip to main content

Production-ready FastAPI backend toolkit with auth, DB, migrations, Redis, ARQ jobs, middleware, logging, pagination, rate limiting, and security helpers.

Project description

Fastvia

Production-ready FastAPI backend toolkit with auth, DB, migrations, Redis, ARQ jobs, middleware, logging, pagination, rate limiting, and security helpers.

Fastvia does not take over your application.
You still create your own FastAPI app, routers, lifespan, database models, and business logic. Fastvia gives you clean reusable building blocks for the parts most production APIs need.

The PyPI distribution name is fastvia-kit, while the Python import package is fastvia.

Installation

pip install fastvia-kit

If you also want Uvicorn for running a FastAPI app:

pip install "fastvia-kit[server]"

For development:

make install-dev

What Fastvia Provides

  • Request context middleware with request ID and process time
  • Security headers middleware
  • Logging context with text and JSON formatters
  • API error classes and exception handlers
  • Pagination helpers
  • Redis-backed rate limiting with SlowAPI
  • Async SQLAlchemy database helpers
  • Redis client helpers
  • ARQ job helpers
  • JWT/FastAPI Users auth helpers
  • Alembic migration helpers
  • Bootstrap helper for existing FastAPI apps

Quick Start

You create your FastAPI app normally:

from fastapi import FastAPI

from fastvia import bootstrap_fastvia

app = FastAPI(
    title="My API",
    version="1.0.0",
)

bootstrap_fastvia(
    app,
    logger_name="myapi",
    log_format="json",
    cors_origins=["http://localhost:3000"],
    rate_limit_storage_uri="redis://localhost:6379/0",
)

This can configure:

  • logging
  • request context middleware
  • security headers
  • error handlers
  • CORS
  • GZip
  • rate limiting

Example

A small runnable FastAPI example is available in:

examples/basic_app.py

Install Fastvia with server support first:

pip install "fastvia-kit[server]"

Run the example app:

uvicorn examples.basic_app:app --reload

Then open:

http://127.0.0.1:8000/docs

The example shows:

  • Fastvia bootstrap setup
  • request context headers
  • security headers
  • pagination
  • API errors
  • rate limiting

Request Context Middleware

from fastapi import FastAPI

from fastvia.middleware import RequestContextMiddleware

app = FastAPI()
app.add_middleware(RequestContextMiddleware)

Each response includes:

x-request-id
x-process-time

The request context is also connected to Fastvia logging.

Security Headers Middleware

from fastvia.middleware import SecurityHeadersMiddleware

app.add_middleware(
    SecurityHeadersMiddleware,
    enable_hsts=True,
)

By default, Fastvia adds common security headers such as:

  • X-Content-Type-Options
  • X-Frame-Options
  • Referrer-Policy
  • Permissions-Policy
  • Cache-Control
  • Content-Security-Policy

You can customize or disable values when needed.

Logging

from fastvia.logging import setup_logging, log_extra

logger = setup_logging(
    level="INFO",
    log_format="json",
    logger_name="myapi",
)

logger.info(
    "Event processed",
    extra=log_extra(
        event_id="evt_123",
        event_type="demo.event.success",
    ),
)

Fastvia supports request-scoped log context:

request_id
method
path
event_id
event_type

API Errors

from fastapi import FastAPI

from fastvia.errors import NotFoundError, register_exception_handlers
from fastvia.middleware import RequestContextMiddleware

app = FastAPI()
app.add_middleware(RequestContextMiddleware)
register_exception_handlers(app)


@app.get("/items/{item_id}")
async def get_item(item_id: int):
    raise NotFoundError("Item not found.")

Example response:

{
  "error": "not_found",
  "message": "Item not found.",
  "details": {},
  "request_id": "..."
}

Pagination

from fastapi import Depends
from pydantic import BaseModel

from fastvia.pagination import (
    PageMeta,
    PaginatedResponse,
    PaginationParams,
    pagination_params,
)


class ItemOut(BaseModel):
    id: int
    name: str


@app.get("/items", response_model=PaginatedResponse[ItemOut])
async def list_items(
    pagination: PaginationParams = Depends(pagination_params),
):
    rows = [
        ItemOut(id=1, name="First"),
        ItemOut(id=2, name="Second"),
    ]
    total = 2

    meta = PageMeta.from_pagination(
        total=total,
        pagination=pagination,
    )

    return PaginatedResponse(
        items=rows,
        meta=meta,
    )

Response shape:

{
  "items": [],
  "meta": {
    "total": 42,
    "page": 2,
    "per_page": 10,
    "pages": 5,
    "has_next": true,
    "has_prev": true
  }
}

Rate Limiting

from fastapi import Request

from fastvia.rate_limit import register_rate_limiting

limiter = register_rate_limiting(
    app,
    storage_uri="redis://localhost:6379/0",
    default_limits=[],
)


@app.get("/ping")
@limiter.limit("10/minute")
async def ping(request: Request):
    return {"message": "pong"}

For authenticated user-based keys:

from fastvia.auth import get_user_id_from_bearer_token
from fastvia.rate_limit import user_or_ip_key

key_func = user_or_ip_key(
    user_id_resolver=lambda request: get_user_id_from_bearer_token(
        request,
        secret="secret",
        algorithm="HS256",
    )
)

limiter = register_rate_limiting(
    app,
    storage_uri="redis://localhost:6379/0",
    key_func=key_func,
)

Database Helpers

from fastvia.db import (
    create_async_db_engine,
    create_session_dependency,
    create_session_factory,
)

engine = create_async_db_engine(
    "postgresql+asyncpg://user:password@localhost/db",
)

SessionLocal = create_session_factory(engine)

get_db = create_session_dependency(SessionLocal)

Then use it in routes:

from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession


@app.get("/items")
async def list_items(db: AsyncSession = Depends(get_db)):
    ...

Redis Helper

from fastvia.redis import close_all_redis, get_redis

redis = get_redis("redis://localhost:6379/0")

await redis.set("key", "value")

Close clients during shutdown:

await close_all_redis()

ARQ Helpers

from fastvia.jobs import create_arq_pool

arq_pool = await create_arq_pool("redis://localhost:6379/0")

Fastvia also provides JSON job serializer/deserializer helpers.

Auth Helpers

Fastvia provides helpers for FastAPI Users JWT auth setup:

from fastvia.auth import create_jwt_auth_backend

auth_backend = create_jwt_auth_backend(
    secret="secret",
    lifetime_seconds=3600,
    algorithm="HS256",
    token_url="/auth/login",
)

It also provides helpers for wiring FastAPI Users dependencies while keeping your app-specific UserManager, email verification, reset password, and user model inside your own project.

Alembic Migration Helpers

from fastvia.migrations import create_alembic_config, upgrade_to_head

config = create_alembic_config(
    config_path="alembic.ini",
    database_url="postgresql+asyncpg://user:password@localhost/db",
)

upgrade_to_head(config)

Fastvia does not run migrations automatically.
Migrations should be explicit, especially in production.

Development

Install development dependencies:

make install-dev

Run tests:

make test

Run tests with coverage:

make test-cov

Format code:

make format

Lint code:

make lint

Clean build and cache files:

make clean

Build package:

make build

Check package:

make check

Equivalent raw commands:

pip install -e ".[dev]"
pytest
pytest --cov=fastvia --cov-report=term-missing
ruff format .
ruff check . --fix
python -m build
twine check dist/*

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastvia_kit-0.1.1.tar.gz (23.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastvia_kit-0.1.1-py3-none-any.whl (23.8 kB view details)

Uploaded Python 3

File details

Details for the file fastvia_kit-0.1.1.tar.gz.

File metadata

  • Download URL: fastvia_kit-0.1.1.tar.gz
  • Upload date:
  • Size: 23.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for fastvia_kit-0.1.1.tar.gz
Algorithm Hash digest
SHA256 c25ce3972bca3fc38dbcd1cd0642d94ed1fe5c5f39317831212a1520994b68cc
MD5 e81eeeaea0d4e864552851b759ecb4f0
BLAKE2b-256 2a9083e0dc3df05b1a3a360dc9b59c12798ef5167f1b69da6cff908b8769f64c

See more details on using hashes here.

File details

Details for the file fastvia_kit-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: fastvia_kit-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 23.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for fastvia_kit-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 cd7e0a81beb65491f65741651674ca9ff215da85aa86e3ac33d4819fda27a69b
MD5 f7746871d5ed297332e003419f1e509c
BLAKE2b-256 84efda4a630e0804a63136cf092cf32e702caf0bfdb08a53d2d6fc3e4872a68d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page