SA

Sanic

Async Python web framework focused on performance with built-in WebSocket support

Details

Language / Topic
pythonPython
Category
framework

Rules

balanced
- Define routes with `@app.get('/users/<user_id:int>')` decorators — Sanic infers the type from the path converter (`int`, `str`, `uuid`).
- Access path params as function arguments: `async def get_user(request, user_id: int)` — Sanic injects typed path params automatically.
- Return `json(data)`, `text(message)`, or `HTTPResponse` from `sanic.response` — never return raw dicts.
- Use `app.blueprint(bp)` to group related routes under a `Blueprint` object for modular organization.
- Read query params with `request.args.get('page', '1')` and JSON body with `request.json`.
- Register routes with decorators: `@app.route('/users/<user_id:int>', methods=['GET', 'PUT'])` or shorthand `@app.get('/users/<user_id:int>')` — Sanic parses and casts the path param to the declared type.
- Return typed responses: `from sanic.response import json, text, empty; return json({'id': user.id}, status=201)` for created resources, `empty(status=204)` for deletes, `json({'error': 'not found'}, status=404)` for missing resources.
- Organize routes with `Blueprint`: `users_bp = Blueprint('users', url_prefix='/api/users'); @users_bp.get('/<user_id:int>')` and register with `app.blueprint(users_bp)`.
- Use `app.add_task(background_fn())` for fire-and-forget async work that runs on the server event loop.
- Apply middleware with `@app.middleware('request')` and `@app.middleware('response')` — request middleware runs before the handler, response middleware after.
- Handle errors globally: `@app.exception(SanicException) async def handle_sanic_error(request, exception): return json({'error': str(exception)}, status=exception.status_code)`.