Swagger/OpenAPI Docs
Xyra can automatically generate interactive API documentation for your application using Swagger UI. This is a powerful feature for developing and testing your API.
Enabling Swagger
To enable Swagger, provide a swagger_options dictionary when creating the App instance. The title and version fields are required.
from xyra import App
swagger_options = {
"title": "My Awesome API",
"version": "1.0.0",
"url": "/docs" # The URL to access the Swagger UI
}
app = App(swagger_options=swagger_options)
Documenting Routes
Xyra automatically generates API documentation from your route handlers' docstrings. Use standard Python docstrings to provide summary, description, and parameter information.
from xyra import App, Request, Response
app = App(swagger_options={"title": "My API", "version": "1.0.0"})
@app.get("/users")
def get_users(req: Request, res: Response):
"""
Get all users in the system.
Returns a list of all registered users with their basic information.
"""
res.json([{"id": 1, "name": "John Doe"}])
@app.post("/users")
async def create_user(req: Request, res: Response):
"""
Create a new user.
Accepts user data in JSON format and creates a new user account.
"""
user_data = await req.json()
res.status(201).json({"message": "User created", "user": user_data})
For more detailed documentation, you can include parameter information in your docstrings:
@app.get("/users/{user_id}")
def get_user(req: Request, res: Response, user_id: int):
"""
Get a specific user by ID.
user_id (int): The unique identifier of the user to retrieve.
"""
# Implementation here
pass
Path Parameters
Path parameters in your routes are automatically detected and documented. Use curly braces in your route paths:
@app.get("/users/{user_id}")
def get_user(req: Request, res: Response, user_id: int):
"""
Get user by ID.
user_id (int): The user identifier.
"""
res.json({"id": user_id, "name": "User Name"})
Advanced Configuration
You can customize the Swagger documentation with additional options in the swagger_options dictionary:
swagger_options = {
"title": "My API",
"version": "1.0.0",
"description": "A comprehensive API for managing users and data",
"url": "/docs",
"contact": {
"name": "API Support",
"email": "support@example.com"
},
"license": {
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
}
}
app = App(swagger_options=swagger_options)
Accessing the Documentation
Once your application is running, you can access the Swagger UI at the URL specified in swagger_options (e.g., http://localhost:8000/docs). This interactive page allows you to explore your API endpoints, view request/response schemas, and send test requests directly from the browser.
The documentation is automatically generated from your route definitions, docstrings, and type annotations, providing an up-to-date reference for your API.