OpenAPI Documentation¶
Django-Bolt automatically generates OpenAPI documentation for your API. This guide covers how to configure and customize the documentation.
Accessing the documentation¶
By default, Django-Bolt serves multiple documentation UIs automatically:
| Path | UI |
|---|---|
/docs |
Swagger UI (default) |
/docs/redoc |
Redoc |
/docs/scalar |
Scalar |
/docs/rapidoc |
RapiDoc |
/docs/stoplight |
Stoplight Elements |
/docs/openapi.json |
Raw JSON schema |
/docs/openapi.yaml |
Raw YAML schema |
Start your server and visit any of these URLs to browse your API documentation.
Configuring OpenAPI¶
Customize the documentation using OpenAPIConfig:
from django_bolt import BoltAPI
from django_bolt.openapi import OpenAPIConfig
api = BoltAPI(
openapi_config=OpenAPIConfig(
title="My API",
version="1.0.0",
description="API for my application",
enabled=True,
)
)
Available options¶
OpenAPIConfig(
title="My API", # API title
version="1.0.0", # API version
description="Description", # API description
enabled=True, # Enable/disable docs
path="/docs", # Docs URL. The schema is at {path}/openapi.json
auth=None, # Auth backends for the docs routes
guards=None, # Guards for the docs routes
strict=False, # Fail generation on untypeable shapes (see below)
)
Strict mode¶
Set OpenAPIConfig(strict=True) to make schema generation fail on shapes that
client code generators cannot type. SchemaGenerator.generate() raises
OpenAPIStrictError. The error lists all problems at the same time. These are
the problems:
- A route has the success response
{"type": "object"}. The route has no return annotation and noresponse_model. - A component name uses the long form
module.qualname. This occurs when two types have the same short name. - The
error_formatterof the API has noerror_schema, and a route has a 422, 401 or 403 response. See OpenAPI schema.
Routes with include_in_schema=False are not problems. Routes with a non-JSON
response_class are not problems. Run strict mode in CI to keep the generated
clients correct.
Documenting endpoints¶
Summary and description¶
@api.get(
"/users/{user_id}",
summary="Get a user",
description="Retrieve a user by their unique ID.",
tags=["users"]
)
async def get_user(user_id: int):
"""
This docstring also appears in the documentation.
Additional details about the endpoint can go here.
"""
return {"user_id": user_id}
Tags¶
Group endpoints using tags:
@api.get("/users", tags=["users"])
async def list_users():
return []
@api.post("/users", tags=["users"])
async def create_user():
return {}
@api.get("/articles", tags=["articles"])
async def list_articles():
return []
Tags appear as sections in the Swagger UI.
Response models¶
Document response schemas:
import msgspec
class User(msgspec.Struct):
id: int
username: str
email: str
@api.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int):
return {"id": user_id, "username": "john", "email": "john@example.com"}
The schema is automatically generated from the msgspec.Struct.
Per-status-code response schemas¶
When response_model is a dict mapping status codes to types, the OpenAPI schema generates a separate response entry for each status code:
@api.get("/items/{item_id}", response_model={200: Item, 404: Error})
async def get_item(item_id: int):
...
This produces OpenAPI responses with both 200 and 404 entries, each with their own schema.
Using ... (ellipsis) as a key emits a "default" response entry in the OpenAPI spec, which represents any status code not explicitly listed:
@api.get("/items/{item_id}", response_model={200: Item, ...: Error})
async def get_item(item_id: int):
...
Using {204: None} generates a response entry with no content body, appropriate for No Content responses.
Request body schemas¶
Request bodies are documented automatically:
class CreateUser(msgspec.Struct):
username: str
email: str
password: str
@api.post("/users")
async def create_user(user: CreateUser):
return {"id": 1, "username": user.username}
A Serializer has two schemas if its input and its output do not have the same fields. The request body schema has no read_only field and no computed field. The response schema has no write_only field. It marks each read_only field and each computed field readOnly: true. If the API uses the serializer for the two, the response uses the component <Name> and the request body uses the component <Name>Input. See Read-only fields.
Status codes¶
Document the default status code:
Error responses¶
The schema shows a 422 response for each route whose input Bolt validates.
Such a route has a path, query, header or cookie parameter, or a request body.
A route with no parameter and no body has no 422. Set
OpenAPIConfig(include_error_responses=False) to remove these responses.
Without a formatter, the 422 body is {"detail": ...}. For a route with only a
JSON body, detail is a list of field errors. For a route with a parameter or
a form field, detail is a list of field errors or a text. Bolt sends the text
for a missing value and for a value of the wrong type. With
BoltAPI(error_formatter=...), the 422 shows the body of the formatter. A route
that declares its own 422 in response_model keeps it. The 422 also shows the
validation body when the API has no formatter, or a formatter with
error_schema. See OpenAPI schema.
Authentication¶
A route with an auth backend gets a security requirement. The list has one
entry for each backend of the route. A request needs only one of them. Each
scheme is in components.securitySchemes:
| Backend | Scheme name | Scheme |
|---|---|---|
JWTAuthentication() |
BearerAuth |
http, bearer, format JWT |
JWTAuthentication(cookie="name") |
JWTCookieAuth |
apiKey in the cookie name |
JWTAuthentication(header="X-Token") |
JWTHeaderAuth |
apiKey in the header X-Token |
APIKeyAuthentication() |
ApiKeyAuth |
apiKey in the header of the backend |
SessionAuthentication() |
SessionAuth |
apiKey in the session cookie |
Two backends of one kind can read from different places, for example two API
key headers. The second place gets its own scheme, such as ApiKeyAuth2. A
scheme in OpenAPIConfig(components=...) with one of these names stays as you
wrote it.
The schema also shows the error responses that the guards of such a route can send:
- 401 for a route with
IsAuthenticatedorRequires. The response has theWWW-Authenticateheader. - 403 for a route with
Requires. This guard can deny a user. - 302 in place of the 401 for a route with
SessionAuthentication(login_url=...). The response has theLocationheader.
The body is {"detail": "<message>"}, or the body of the error_formatter of
the API. A route with no auth backend has none of these responses. A route with
no guard, or with AllowAny as its first guard, has none of them.
OpenAPIConfig(include_error_responses=False) removes them.
Customizing documentation UIs¶
By default, all documentation UIs are served automatically. To serve only specific UIs, provide a custom render_plugins list:
Swagger UI only¶
from django_bolt.openapi import OpenAPIConfig, SwaggerRenderPlugin
api = BoltAPI(
openapi_config=OpenAPIConfig(
title="My API",
version="1.0.0",
render_plugins=[SwaggerRenderPlugin(path="/")],
)
)
ReDoc only¶
from django_bolt.openapi import OpenAPIConfig, RedocRenderPlugin
api = BoltAPI(
openapi_config=OpenAPIConfig(
title="My API",
version="1.0.0",
render_plugins=[RedocRenderPlugin(path="/")],
)
)
Scalar only¶
from django_bolt.openapi import OpenAPIConfig, ScalarRenderPlugin
api = BoltAPI(
openapi_config=OpenAPIConfig(
title="My API",
version="1.0.0",
render_plugins=[ScalarRenderPlugin(path="/")],
)
)
Stoplight Elements only¶
from django_bolt.openapi import OpenAPIConfig, StoplightRenderPlugin
api = BoltAPI(
openapi_config=OpenAPIConfig(
title="My API",
version="1.0.0",
render_plugins=[StoplightRenderPlugin(path="/")],
)
)
RapiDoc only¶
from django_bolt.openapi import OpenAPIConfig, RapidocRenderPlugin
api = BoltAPI(
openapi_config=OpenAPIConfig(
title="My API",
version="1.0.0",
render_plugins=[RapidocRenderPlugin(path="/")],
)
)
Multiple UIs at custom paths¶
from django_bolt.openapi import (
OpenAPIConfig,
SwaggerRenderPlugin,
RedocRenderPlugin,
)
api = BoltAPI(
openapi_config=OpenAPIConfig(
title="My API",
version="1.0.0",
render_plugins=[
SwaggerRenderPlugin(path="/"), # /docs
RedocRenderPlugin(path="/redoc"), # /docs/redoc
],
)
)
Bolt gives the path of OpenAPIConfig and the path of each plugin a leading slash. Thus OpenAPIConfig(path="docs") with RedocRenderPlugin(path="redoc") serves /docs/redoc.
Raw OpenAPI JSON/YAML¶
The raw OpenAPI specification is always available at:
/docs/openapi.json- JSON format/docs/openapi.yaml- YAML format (requirespyyamlpackage)
Protecting documentation¶
The docs routes take auth and guards, as every route does. Without them, the docs use BOLT_AUTHENTICATION_CLASSES and BOLT_DEFAULT_PERMISSION_CLASSES.
Django session authentication¶
A browser does not send a token. Use SessionAuthentication for docs that people open in a browser. Bolt adds Django's session and auth middleware to the docs routes.
This example gives the docs to staff users who logged in to the Django admin:
from django_bolt.auth import Requires, SessionAuthentication
api = BoltAPI(
openapi_config=OpenAPIConfig(
title="My API",
version="1.0.0",
auth=[SessionAuthentication(login_url="/admin/login/")],
guards=[Requires("is_staff", True)],
)
)
- An anonymous user goes to the admin login page. After the login, Django sends the user back to the docs.
- A logged-in user who is not staff gets 403.
- Without
login_url, an anonymous user gets 401.
To let any logged-in user see the docs, use guards=[IsAuthenticated()].
Token authentication¶
Protect the docs with a JWT or an API key. A request with no valid token gets 401 or 403, with no redirect:
from django_bolt.auth import JWTAuthentication, IsAuthenticated
api = BoltAPI(
openapi_config=OpenAPIConfig(
title="My API",
version="1.0.0",
auth=[JWTAuthentication()],
guards=[IsAuthenticated()],
)
)
Disabling documentation¶
Disable documentation in production:
import os
api = BoltAPI(
openapi_config=OpenAPIConfig(
title="My API",
enabled=os.environ.get("DEBUG", "false").lower() == "true",
)
)
Parameter documentation¶
Parameters are documented automatically from function signatures:
@api.get("/search")
async def search(
q: str, # Required query parameter
page: int = 1, # Optional with default
limit: int = 20, # Optional with default
):
"""
Search for items.
- **q**: Search query string (required)
- **page**: Page number (default: 1)
- **limit**: Items per page (default: 20)
"""
return {"query": q, "page": page, "limit": limit}
Hiding endpoints¶
Set include_in_schema=False to remove endpoints from the documentation. The
server continues to serve them. The flag is layered. You can set it on a route,
on a view class, or on a BoltAPI. The most specific layer wins:
@api.get("/internal", include_in_schema=False)
async def internal():
return {"internal": True}
@api.view("/admin", include_in_schema=False)
class AdminView(APIView):
async def get(self):
return {}
class InternalViewSet(ViewSet):
include_in_schema = False # the class attribute is the middle layer
...
# Hide a whole sub-API. A route with include_in_schema=True stays visible.
internal_api = BoltAPI(include_in_schema=False)
api.mount("/internal", internal_api)
The default value at each layer is None. None inherits from the outer layer.
The root BoltAPI resolves None to True.
Deprecating endpoints¶
Set deprecated=True to mark an endpoint as deprecated in the documentation.
The operation gets deprecated: true. The docs UIs show it as deprecated, and
client generators mark its function. The server continues to serve the
endpoint. An endpoint that is not deprecated has no deprecated key:
@api.get("/v1/users", deprecated=True)
async def list_users_v1():
return []
@api.view("/v1/profile", deprecated=True) # each method of the view
class ProfileView(APIView):
async def get(self, request):
return {}
@api.viewset("/items")
class ItemViewSet(ViewSet):
@action(methods=["GET"], detail=False, deprecated=True) # only this action
async def legacy(self, request):
return []
The route decorators of BoltAPI and Router, @api.view(), @api.viewset()
and @action take deprecated. On @api.viewset(), it applies to each route
of the viewset, and also to its @action routes.
Non-JSON responses¶
response_class sets the media type in the documentation. The default is
application/json. A return annotation with one of these classes, for example
-> StreamingResponse, has the same effect:
response_class |
Media type | Schema |
|---|---|---|
HTML |
text/html |
string |
PlainText |
text/plain |
string |
File, FileResponse, StreamingResponse |
application/octet-stream |
string / binary |
EventSourceResponse |
text/event-stream |
string |
Redirect |
none (status 307, or the status_code of the route) |
Location header only |
A route with the return type str shows text/plain. A route with the return
type bytes shows application/octet-stream. Bolt sends these values as they
are, not as JSON.
A union shows one media type for each kind of result. For example,
-> str | None shows text/plain for the string and application/json for
null, and -> str | Item shows text/plain and application/json with the
schema of Item. An entry of a response_model dict follows the same rules:
{200: str, 404: Error} shows text/plain for the status 200.
Each parametrization of a generic response model gets its own component name.
This is the same as msgspec. Page[UserRead] becomes the component
Page_UserRead_. Its title is Page[UserRead].
OpenAPI extensions¶
The generated OpenAPI spec follows the OpenAPI 3.1.0 specification and includes:
- Path parameters with types
- Query parameters with defaults
- Request body schemas from
msgspec.Struct - Response schemas from
response_model - Authentication requirements from
auth=andguards= - Tag grouping
- Operation summaries and descriptions