2.3.1 Uvicorn
Uvicorn is a Python ASGI server. It is commonly used to run FastAPI applications.
Think of it like this:
TEXT
Browser / Client
↓
HTTP
↓
Uvicorn
↓
ASGI
↓
FastAPI
↓
Your Python code
Example
Suppose you have:
PYTHON
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def home():
return {"message": "Hello"}
You run:
BASH
uvicorn main:app
Uvicorn starts a server, usually at:
TEXT
http://127.0.0.1:8000
Then when you visit /:
TEXT
GET /
↓
Uvicorn receives request
↓
ASGI
↓
FastAPI
↓
home()
↓
JSON response
Why Uvicorn is important for async
Uvicorn is designed for ASGI, so it can work with Python's async ecosystem:
PYTHON
@app.get("/users")
async def users():
users = await get_users_from_database()
return users
While your database operation is waiting, the event loop can handle other work.
TEXT
Request A
↓
await database
↓
Event Loop
├── Request B
├── Request C
└── Request D
↓
Database finishes
↓
Resume Request A
Uvicorn vs Gunicorn
The easiest way to remember:
| Uvicorn | Gunicorn | |
|---|---|---|
| Type | ASGI server | Traditionally WSGI server |
| FastAPI | ✅ | Can manage Uvicorn workers |
| Flask | Possible via ASGI adapters | ✅ |
| Async | ✅ | Not traditionally its main model |
| Common use | FastAPI/Starlette | Flask/Django |
For your FastAPI stack, remember this chain:
TEXT
Uvicorn
↓
ASGI
↓
Starlette
↓
FastAPI
↓
Your application
And when you type:
BASH
uvicorn main:app --reload
Uvicorn is the actual server process listening for HTTP requests.