Automatic API Docs¶
Ushka can automatically generate interactive API documentation for your project, inspired by FastAPI. This feature leverages the OpenAPI standard and presents your API through the beautiful Swagger UI.
This allows you to have a live, interactive documentation page where you can explore and test your API endpoints directly from the browser.
How It Works¶
The documentation is generated automatically by inspecting your code:
* Routes: It finds all registered routes from your views.py files.
* Path Parameters: It uses function parameter names and type hints (e.g., user_id: int) to document URL parameters.
* Request Bodies: It uses Form[YourPydanticModel] type hints to generate schemas for your JSON request bodies, including all validation rules from your Pydantic models.
Enabling the API Docs¶
The feature is disabled by default. To enable it, add an [openapi] section to your ushka.toml file.
Once enabled, restart your server. The interactive documentation will be available at /docs.
Configuration Options¶
You can customize the generated documentation from your ushka.toml:
enabled(boolean): Set totrueto enable the feature.title(string): The title of your API, which will be displayed at the top of the Swagger UI.version(string): The version of your API.docs_url(string): The URL path where the interactive Swagger UI will be served. Defaults to/docs.openapi_url(string): The URL path where the rawopenapi.jsonschema file will be served. Defaults to/openapi.json.
Example: Documenting a POST Request¶
Let's see how a typical POST route is documented.
1. Define your Pydantic Model:
This model defines the expected shape and data types for your request body.
# in apps/users/models.py
from pydantic import BaseModel, EmailStr
class UserCreate(BaseModel):
username: str
email: EmailStr
full_name: str | None = None
2. Use the model in your view with Form[T]:
Type-hint a parameter in your view function with Form[UserCreate].
# in apps/users/views.py
from ushka.http import Request, Response
from ushka.forms import Form
from .models import UserCreate
async def post_create(request: Request, form: Form[UserCreate]):
if not form.is_valid:
return Response({"errors": form.errors}, status_code=400)
user_data = form.data
# ... logic to save the new user ...
return Response({
"status": "created",
"user": user_data.model_dump()
}, status_code=201)
When you visit your /docs page, you will now see an entry for POST /users/create. The Swagger UI will show an example payload based on your UserCreate model and allow you to send test requests with automatic validation.