Claude Code for Litestar: High-Performance Python API Framework — Claude Skills 360 Blog
Blog / AI / Claude Code for Litestar: High-Performance Python API Framework
AI

Claude Code for Litestar: High-Performance Python API Framework

Published: December 30, 2027
Read time: 5 min read
By: Claude Skills 360

Litestar is a performant ASGI API framework. pip install litestar[full]. Route: from litestar import get, post, Litestar. Handler: @get("/users") async def list_users() -> list[User]: return []. App: app = Litestar(route_handlers=[list_users]). Run: uvicorn app:app. Path params: @get("/users/{user_id:int}"). Query params: async def fn(page: int = 1, limit: int = 20). Request body: @post("/users") async def create(data: CreateUserDTO) -> UserDTO. DTOs: from litestar.dto import DataclassDTO, SQLAlchemyDTO. Dependency injection: from litestar.di import Provide. @get("/", dependencies={"repo": Provide(get_repo)}). Guard: class AuthGuard(Guard): async def __call__(self, connection, handler): if not connection.user: raise NotAuthorizedException(). @get("/admin", guards=[AuthGuard()]). Middleware: from litestar.middleware import AbstractMiddleware. Router: Router(path="/api/v1", route_handlers=[users_router, orders_router]). Exception handler: @app.exception_handler(ValidationException). Response: Response(content=data, status_code=201, headers={...}). Status codes: @get(status_code=200). OpenAPI: auto-generated at /schema. @get(summary="List users", operation_id="listUsers"). Pagination: from litestar.pagination import CursorPagination, OffsetPagination. AbstractRepository: class UserRepo(AbstractRepository[User]): async def get(self, id): .... SQLAlchemyAsyncRepository(model_type=User, session=session). Params: field_definitions = {FieldDefinition.from_annotation(str, name="email")}. Testing: from litestar.testing import AsyncTestClient. async with AsyncTestClient(app) as client: resp = await client.get("/users"). Lifespan events: @on_startup, @on_shutdown. app.on_startup.append(init_db). Claude Code generates Litestar route handlers, DTO definitions, Guard implementations, and test suites.

CLAUDE.md for Litestar

## Litestar Stack
- Version: litestar >= 2.9 | pip install "litestar[full]"
- Route: @get @post @put @patch @delete decorators with path + type hints
- DI: dependencies={"name": Provide(factory_fn)} per route or router
- DTO: DataclassDTO[ModelClass] | from_encodable for custom serialization
- Guard: class G(Guard): async def __call__(connection, handler): raise if denied
- Router: Router(path="/api/v1", route_handlers=[...]) for modular groups
- Test: AsyncTestClient(app) — full ASGI test client, no server needed

Litestar API Pipeline

# app/litestar_app.py — Litestar API with routing, DI, DTOs, guards, and tests
from __future__ import annotations

import logging
from dataclasses import dataclass, field
from datetime import datetime
from typing import Annotated, Optional
from uuid import UUID, uuid4

from litestar import Litestar, MediaType, Router, delete, get, patch, post, put
from litestar.connection import ASGIConnection
from litestar.datastructures import State
from litestar.di import Provide
from litestar.dto import DataclassDTO
from litestar.exceptions import (
    HTTPException,
    NotAuthorizedException,
    NotFoundException,
    ValidationException,
)
from litestar.handlers import BaseRouteHandler
from litestar.middleware import AbstractMiddleware
from litestar.openapi.config import OpenAPIConfig
from litestar.openapi.spec import Contact
from litestar.pagination import OffsetPagination
from litestar.params import Parameter
from litestar.response import Response
from litestar.security.abstract import AbstractSecurityConfig
from litestar.status_codes import HTTP_201_CREATED, HTTP_204_NO_CONTENT
from litestar.testing import AsyncTestClient
from litestar.types import Guard

logger = logging.getLogger(__name__)


# ─────────────────────────────────────────────────────────────────────────────
# Data models (dataclasses — DTO works with plain dataclasses)
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class Address:
    street:      str
    city:        str
    state:       str
    postal_code: str


@dataclass
class User:
    id:         UUID
    email:      str
    first_name: str
    last_name:  str
    role:       str        = "user"
    is_active:  bool       = True
    address:    Optional[Address] = None
    created_at: datetime   = field(default_factory=datetime.utcnow)


@dataclass
class CreateUserRequest:
    email:      str
    first_name: str
    last_name:  str
    password:   str
    role:       str = "user"


@dataclass
class UpdateUserRequest:
    first_name: Optional[str] = None
    last_name:  Optional[str] = None
    role:       Optional[str] = None


# ─────────────────────────────────────────────────────────────────────────────
# DTO classes — control which fields are exposed
# ─────────────────────────────────────────────────────────────────────────────

class UserResponseDTO(DataclassDTO[User]):
    """Response DTO — exposes all fields except those excluded below."""
    config = DataclassDTO.generate_config(exclude=frozenset())


class CreateUserDTO(DataclassDTO[CreateUserRequest]):
    """Request DTO for creating users — excludes password from response."""
    pass


# ─────────────────────────────────────────────────────────────────────────────
# In-memory repository (replace with SQLAlchemy in production)
# ─────────────────────────────────────────────────────────────────────────────

class UserRepository:
    def __init__(self) -> None:
        self._store: dict[UUID, User] = {}
        # Seed some data
        for name, email in [("Alice Smith", "[email protected]"),
                             ("Bob Jones",   "[email protected]")]:
            first, last = name.split()
            u = User(id=uuid4(), email=email, first_name=first, last_name=last)
            self._store[u.id] = u

    def list(self, page: int = 1, page_size: int = 20) -> tuple[list[User], int]:
        all_users = list(self._store.values())
        total = len(all_users)
        start = (page - 1) * page_size
        return all_users[start: start + page_size], total

    def get(self, user_id: UUID) -> User:
        user = self._store.get(user_id)
        if user is None:
            raise NotFoundException(detail=f"User {user_id} not found")
        return user

    def create(self, data: CreateUserRequest) -> User:
        if any(u.email == data.email for u in self._store.values()):
            raise HTTPException(status_code=409, detail="Email already in use")
        user = User(
            id=uuid4(),
            email=data.email,
            first_name=data.first_name,
            last_name=data.last_name,
            role=data.role,
        )
        self._store[user.id] = user
        return user

    def update(self, user_id: UUID, updates: UpdateUserRequest) -> User:
        user = self.get(user_id)
        if updates.first_name: user.first_name = updates.first_name
        if updates.last_name:  user.last_name  = updates.last_name
        if updates.role:       user.role       = updates.role
        return user

    def delete(self, user_id: UUID) -> None:
        self.get(user_id)   # raises NotFoundException if absent
        del self._store[user_id]


# Singleton for demo (use DI factory in production)
_REPO = UserRepository()


def get_user_repo() -> UserRepository:
    return _REPO


# ─────────────────────────────────────────────────────────────────────────────
# Guards
# ─────────────────────────────────────────────────────────────────────────────

async def require_authenticated(
    connection: ASGIConnection,
    handler:    BaseRouteHandler,
) -> None:
    """Check that the request carries a valid token (header-based for demo)."""
    auth_header = connection.headers.get("authorization", "")
    if not auth_header.startswith("Bearer "):
        raise NotAuthorizedException(detail="Bearer token required")


async def require_admin(
    connection: ASGIConnection,
    handler:    BaseRouteHandler,
) -> None:
    """Check the token encodes admin role (simplified — use JWT in production)."""
    auth_header = connection.headers.get("authorization", "")
    if "admin-token" not in auth_header:
        raise NotAuthorizedException(detail="Admin access required")


# ─────────────────────────────────────────────────────────────────────────────
# Route handlers
# ─────────────────────────────────────────────────────────────────────────────

@get("/")
async def health() -> dict:
    return {"status": "ok", "version": "1.0"}


@get(
    "/users",
    return_dto=UserResponseDTO,
)
async def list_users(
    repo:      UserRepository,
    page:      Annotated[int, Parameter(ge=1, default=1)],
    page_size: Annotated[int, Parameter(ge=1, le=100, default=20)],
) -> OffsetPagination[User]:
    items, total = repo.list(page=page, page_size=page_size)
    return OffsetPagination[User](
        items=items,
        total=total,
        limit=page_size,
        offset=(page - 1) * page_size,
    )


@get(
    "/users/{user_id:uuid}",
    return_dto=UserResponseDTO,
)
async def get_user(user_id: UUID, repo: UserRepository) -> User:
    return repo.get(user_id)


@post(
    "/users",
    dto=CreateUserDTO,
    return_dto=UserResponseDTO,
    status_code=HTTP_201_CREATED,
    guards=[require_authenticated],
)
async def create_user(data: CreateUserRequest, repo: UserRepository) -> User:
    return repo.create(data)


@patch(
    "/users/{user_id:uuid}",
    return_dto=UserResponseDTO,
    guards=[require_authenticated],
)
async def update_user(
    user_id: UUID,
    data:    UpdateUserRequest,
    repo:    UserRepository,
) -> User:
    return repo.update(user_id, data)


@delete(
    "/users/{user_id:uuid}",
    status_code=HTTP_204_NO_CONTENT,
    guards=[require_admin],
)
async def delete_user(user_id: UUID, repo: UserRepository) -> None:
    repo.delete(user_id)


# ─────────────────────────────────────────────────────────────────────────────
# Router — group related handlers
# ─────────────────────────────────────────────────────────────────────────────

users_router = Router(
    path="/api/v1",
    route_handlers=[list_users, get_user, create_user, update_user, delete_user],
    dependencies={"repo": Provide(get_user_repo, sync_to_thread=False)},
    tags=["Users"],
)

# ─────────────────────────────────────────────────────────────────────────────
# Application
# ─────────────────────────────────────────────────────────────────────────────

app = Litestar(
    route_handlers=[health, users_router],
    openapi_config=OpenAPIConfig(
        title="Demo API",
        version="1.0.0",
        contact=Contact(name="Engineering", email="[email protected]"),
    ),
    debug=False,
)


# ─────────────────────────────────────────────────────────────────────────────
# Tests
# ─────────────────────────────────────────────────────────────────────────────

async def run_tests() -> None:
    async with AsyncTestClient(app=app) as client:
        # Health check
        response = await client.get("/")
        assert response.status_code == 200
        assert response.json()["status"] == "ok"

        # List users
        response = await client.get("/api/v1/users")
        assert response.status_code == 200
        users = response.json()
        assert users["total"] >= 2

        # Get specific user
        user_id = users["items"][0]["id"]
        response = await client.get(f"/api/v1/users/{user_id}")
        assert response.status_code == 200

        # Create user without auth — should fail
        response = await client.post("/api/v1/users", json={
            "email": "[email protected]", "first_name": "New",
            "last_name": "User", "password": "pass123"})
        assert response.status_code == 401

        # Create user with auth token
        response = await client.post(
            "/api/v1/users",
            json={"email": "[email protected]", "first_name": "New",
                  "last_name": "User", "password": "pass123"},
            headers={"Authorization": "Bearer some-token"},
        )
        assert response.status_code == 201
        new_id = response.json()["id"]

        # Delete without admin — should fail
        response = await client.delete(
            f"/api/v1/users/{new_id}",
            headers={"Authorization": "Bearer some-token"},
        )
        assert response.status_code == 401

        # Delete with admin token
        response = await client.delete(
            f"/api/v1/users/{new_id}",
            headers={"Authorization": "Bearer admin-token"},
        )
        assert response.status_code == 204

        print("All tests passed.")


if __name__ == "__main__":
    import asyncio, uvicorn  # noqa: E401
    asyncio.run(run_tests())
    uvicorn.run("app.litestar_app:app", host="0.0.0.0", port=8000, reload=True)

For the FastAPI alternative — FastAPI uses Pydantic models in function signatures for both validation and OpenAPI schema generation, while Litestar’s DTO layer separates the ORM/dataclass from what is serialized: DataclassDTO.generate_config(exclude=frozenset({"password"})) strips the password from the response without a separate response model class, annotations.Guard guards execute before the handler and raise NotAuthorizedException or PermissionDeniedException with structured error payloads, and OffsetPagination returns a standard {"items": [...], "total": N, "limit": N, "offset": N} shape from any handler returning a list. For the Django REST Framework alternative — DRF is synchronous and requires Serializer, ViewSet, permissions.IsAuthenticated, and a router.register() call for each resource, while Litestar’s @get("/users/{user_id:uuid}") handles path parameter parsing, Parameter(ge=1, le=100) validates query params, and Provide(get_repo, sync_to_thread=False) injects the repository without a class-based view — async all the way. The Claude Skills 360 bundle includes Litestar skill sets covering get/post/put/patch/delete decorators, DataclassDTO for request and response shaping, Provide dependency injection, Guard for route authorization, Router for modular grouping, Parameter for query param validation, OffsetPagination, AsyncTestClient for testing, OpenAPIConfig schema generation, and middleware integration. Start with the free tier to try high-performance API code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free