Skip to content

What it is

Sanic is a Python 3.7+ web server and web framework that’s designed for fast HTTP responses using asynchronous capabilities powered by `asyncio`. It is ideal for building high-performance APIs and web applications.

Sanic allows defining routes with async request handlers, middleware, blueprints, and WebSocket support. It emphasizes high performance while maintaining simple and readable syntax.

Installation

pip install sanic

Getting started

The smallest useful thing you can do with it, and what each part means.

Simple Hello World App
from sanic import Sanic
from sanic.response import text

app = Sanic('my_app')

@app.get('/')
async def hello(request):
    return text('Hello, Sanic!')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)
Creates a basic Sanic app with a single GET route that responds with 'Hello, Sanic!'.
Dynamic Route with URL Parameter
from sanic import Sanic
from sanic.response import json

app = Sanic('my_app')

@app.get('/user/<name>')
async def greet_user(request, name):
    return json({'message': f'Hello, {name}!'})

app.run(host='0.0.0.0', port=8000)
Defines a dynamic route that captures the `<name>` parameter from the URL and returns it in a JSON response.

Advanced usage

Where the library earns its place over a simpler alternative.

Middleware Example
from sanic import Sanic
from sanic.response import text

app = Sanic('my_app')

@app.middleware('request')
async def print_request(request):
    print(f'Received request: {request.method} {request.path}')

@app.get('/')
async def hello(request):
    return text('Hello, Sanic!')

app.run(host='0.0.0.0', port=8000)
Demonstrates request middleware that executes before each request, logging method and path.
Using Blueprints
from sanic import Sanic, Blueprint
from sanic.response import json

bp = Blueprint('api')

@bp.get('/status')
async def status(request):
    return json({'status': 'ok'})

app = Sanic('my_app')
app.blueprint(bp, url_prefix='/api')

app.run(host='0.0.0.0', port=8000)
Shows how to modularize routes using Blueprints and a URL prefix.
WebSocket Example
from sanic import Sanic
from sanic.websocket import WebSocketProtocol

app = Sanic('my_app')

@app.websocket('/feed')
async def feed(request, ws):
    while True:
        data = await ws.recv()
        await ws.send(f'Received: {data}')

app.run(host='0.0.0.0', port=8000, protocol=WebSocketProtocol)
Implements a WebSocket route that echoes back messages received from the client.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

SanicException
Use try/except blocks in handlers or Sanic’s error handlers to manage exceptions gracefully.
Invalid usage of async/await
Ensure all route handlers performing I/O operations are defined as async functions.

Best practices

  • Use async request handlers to leverage non-blocking performance.
  • Organize large applications using Blueprints for modular routing.
  • Use middleware for authentication, logging, and request preprocessing.
  • Leverage Sanic’s built-in support for HTTP/2 for improved speed.
  • Monitor performance using Sanic’s built-in metrics or custom logging.

Background

Why it exists, and what it was reacting to.

Sanic was created by Kenneth Reitz in 2016 to provide an asynchronous Python web framework capable of handling high loads efficiently. It leverages Python's `async`/`await` syntax for non-blocking request handling and has been adopted for real-time APIs and web services requiring speed.