OpenAPI Schemas
Relevant source files
The following files were used as context for generating this wiki page:
The OpenAPI Schema system in Starlette provides automated tools for generating API documentation based on the application's routing structure and endpoint docstrings. It allows developers to define a base schema and automatically populate the paths section by introspecting registered routes.
This functionality is primarily driven by the SchemaGenerator class, which traverses the application's route tree, extracts YAML-formatted metadata from function docstrings, and compiles a comprehensive OpenAPI-compliant dictionary. This dictionary can then be served via a specialized response type.
Sources: starlette/schemas.py:1-133, README.md:1-105
Core Components
The schema generation system is built around several key classes and data structures that handle route introspection and documentation parsing.
SchemaGenerator and BaseSchemaGenerator
BaseSchemaGenerator defines the interface for generating schemas, while SchemaGenerator provides the standard implementation. The generator takes a base_schema dictionary (containing top-level OpenAPI fields like info and openapi version) and populates the paths key.
Sources: starlette/schemas.py:116-133
EndpointInfo
A NamedTuple used during route traversal to store normalized endpoint data.
path: The URL path of the endpoint.http_method: The lowercase HTTP method (e.g., 'get', 'post').func: The underlying Python callable (function or method) to be introspected for docstrings.
Sources: starlette/schemas.py:27-30
OpenAPIResponse
A specialized Response class that sets the media_type to application/vnd.oai.openapi and uses pyyaml to render the schema dictionary into a YAML string.
Sources: starlette/schemas.py:17-24
Architecture and Data Flow
The generation process involves recursively walking through a list of routes. The system handles standard Route objects, Mount points (sub-applications), and Host routes.
This diagram shows the logical flow from a list of Starlette routes to a finalized OpenAPI dictionary.
Sources: starlette/schemas.py:36-96
Route Introspection Logic
The generator identifies endpoints based on the type of route.endpoint:
- Function/Method: If the endpoint is a function, it iterates through
route.methods(defaulting to GET) and creates anEndpointInfofor each. - Class-based (HTTPEndpoint): If the endpoint is a class, it checks for methods named
get,post,put,patch,delete, oroptionsand includes those that exist.
Sources: starlette/schemas.py:69-86, starlette/routing.py:408-430
Path Normalization
Starlette uses a specific syntax for path parameters (e.g., /{id:int}). The schema generator includes a _remove_converter helper that strips these type hints to comply with the standard OpenAPI path template format (e.g., /{id}).
Sources: starlette/schemas.py:33, 98-106
Schema Definition in Docstrings
Endpoint metadata is defined directly in the Python docstrings using YAML format. The generator looks for a --- separator to distinguish between regular documentation and the OpenAPI schema fragment.
Docstring Parsing Process
The sequence of extracting YAML content from a function's docstring.
Sources: starlette/schemas.py:108-123, tests/test_schemas.py:23-45
Example Configuration
| Element | Requirement | Description |
|---|---|---|
| Dependency | pyyaml | Must be installed to parse docstrings and render OpenAPIResponse. |
| Separator | --- | Optional; used to separate standard text from the YAML schema. |
| Format | YAML | Must be a valid YAML dictionary once parsed. |
Sources: starlette/schemas.py:110, 119, pyproject.toml:44
Implementation Example
The following code illustrates how to set up a schema endpoint within a Starlette application.
from starlette.schemas import SchemaGenerator
from starlette.applications import Starlette
from starlette.routing import Route
schemas = SchemaGenerator(
{"openapi": "3.0.0", "info": {"title": "API", "version": "1.0"}}
)
def list_users(request):
"""
responses:
200:
description: A list of users.
"""
pass
def openapi_schema(request):
return schemas.OpenAPIResponse(request)
app = Starlette(routes=[
Route("/users", list_users, methods=["GET"]),
Route("/schema", openapi_schema, include_in_schema=False)
])
Sources: tests/test_schemas.py:11-100, starlette/applications.py:111-114
Summary
OpenAPI support in Starlette is a modular utility that leverages the existing routing system to generate technical documentation. By using docstrings as the source of truth for endpoint-specific schema fragments, it maintains a close relationship between the code and its documentation while requiring minimal boilerplate configuration.
Sources: starlette/schemas.py:1-133