Skip to content

LightAPI v2 Documentation

LightAPI v2 is a Python REST API framework where a single annotated class simultaneously acts as your SQLAlchemy ORM model, your Pydantic v2 validation schema, and your HTTP endpoint. No more keeping three files in sync — declare once, get everything.

Built on Starlette + Uvicorn, validated by Pydantic v2, persisted via SQLAlchemy 2.0 imperative mapping.


Key Features

One Class, Three Roles

  • Annotation-driven columnstitle: str = Field(min_length=1) creates a VARCHAR NOT NULL column, a Pydantic constraint, and an API validation rule simultaneously
  • Auto-injected audit columns — every endpoint gets id, created_at, updated_at, version automatically
  • Full CRUDGET, POST, PUT, PATCH, DELETE generated from a single class definition

Data Integrity

  • Optimistic locking — every PUT/PATCH requires version in the body; stale writes return 409 Conflict
  • Pydantic v2 validation422 Unprocessable Entity with structured error details on bad input
  • Consistent error format{"detail": "..."} or {"detail": [...pydantic errors...]} across all errors

Security

  • JWT AuthenticationMeta.authentication = Authentication(backend=JWTAuthentication)
  • Permission classesAllowAny, IsAuthenticated, IsAdminUser (checks is_admin JWT claim)
  • CORSLightApi(cors_origins=[...])

Querying

  • Filter backendsFieldFilter (exact match with type coercion), SearchFilter (LIKE), OrderingFilter
  • Pagination — page-number or cursor (keyset) styles via Meta.pagination
  • Custom queryset — override queryset(self, request) to scope the base query

Async I/O (opt-in)

  • Single engine swap — pass create_async_engine(...) instead of create_engine(...) to activate full async I/O
  • Async querysetasync def queryset is detected and awaited automatically
  • Async method overridesasync def post/get/put/patch/delete coexist with sync overrides on the same app
  • Background tasksself.background(fn, *args) schedules post-response fire-and-forget tasks
  • Mixed middlewareasync def process and def process middleware coexist in the same stack
  • Async reflectionMeta.reflect = True works with AsyncEngine via conn.run_sync

Developer Experience

  • Redis cachingMeta.cache = Cache(ttl=60) caches GET responses; writes auto-invalidate
  • HttpMethod mixinsclass MyEp(RestEndpoint, HttpMethod.GET, HttpMethod.POST) for explicit verb control
  • SerializerMeta.serializer = Serializer(read=[...], write=[...]) for per-verb field projection
  • MiddlewareMiddleware.process(request, response) — sync or async — with short-circuit support
  • Database reflection — map existing tables with Meta.reflect = True | "partial"
  • YAML configLightApi.from_config("lightapi.yaml") — declarative endpoints with Pydantic-validated schema

Quick Start

uv add lightapi
from sqlalchemy import create_engine
from lightapi import LightApi, RestEndpoint, Field
from typing import Optional

class BookEndpoint(RestEndpoint):
    title: str = Field(min_length=1)
    author: str = Field(min_length=1)
    year: Optional[int] = None

engine = create_engine("sqlite:///books.db")
app = LightApi(engine=engine)
app.register({"/books": BookEndpoint})
app.run()
uv add "lightapi[async]"
from sqlalchemy.ext.asyncio import create_async_engine
from lightapi import LightApi, RestEndpoint, Field
from typing import Optional

class BookEndpoint(RestEndpoint):
    title: str = Field(min_length=1)
    author: str = Field(min_length=1)
    year: Optional[int] = None

engine = create_async_engine(
    "postgresql+asyncpg://user:pass@localhost/mydb"
)
app = LightApi(engine=engine)
app.register({"/books": BookEndpoint})
app.run()

See the Quickstart Guide for full curl examples.


Documentation

Getting Started

Core Concepts

Async Support

Reference


Requirements

  • Python 3.10+
  • SQLAlchemy 2.x
  • Pydantic v2
  • Starlette + Uvicorn

Async extras (lightapi[async]):

  • sqlalchemy[asyncio]
  • asyncpg (PostgreSQL) or aiosqlite (SQLite)
  • greenlet