Quickstart Guide
Relevant source files
The following files were used as context for generating this wiki page:
Starlette is a lightweight ASGI framework and toolkit designed for building high-performance asyncio services in Python. It can be used as a complete web framework or as a modular toolkit where components are used independently. Starlette provides core web functionalities including routing, middleware support, WebSocket handling, and background tasks while maintaining 100% type annotation and test coverage.
Sources: README.md:16-30, starlette/applications.py:20-22
Installation and Requirements
To begin using Starlette, you must install the core package and an ASGI server to execute the application.
Base Installation
pip install starlette
pip install uvicorn
Sources: README.md:32-42
Optional Dependencies
Starlette maintains a minimal core but supports extra features through optional dependencies:
| Dependency | Purpose | Requirement |
|---|---|---|
httpx | Using the TestClient | httpx>=0.27.0,<0.29.0 |
jinja2 | Template support | jinja2 |
python-multipart | Form parsing (request.form()) | python-multipart>=0.0.18 |
itsdangerous | Session support | itsdangerous |
pyyaml | API Schema generation | pyyaml |
To install all optional features, use pip install starlette[full].
Sources: README.md:57-67, pyproject.toml:44-55
Basic Application Structure
A standard Starlette application involves defining endpoints, configuring routes, and initializing the Starlette application class.
Example: Minimal Web Service
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
async def homepage(request):
return JSONResponse({'hello': 'world'})
routes = [
Route("/", endpoint=homepage)
]
app = Starlette(debug=True, routes=routes)
Sources: README.md:44-55
Request Lifecycle
When a request enters a Starlette application, it passes through a middleware stack before being handled by the router.
The diagram above illustrates the default middleware wrapping order where ServerErrorMiddleware is the outermost layer and ExceptionMiddleware is the innermost layer.
Sources: starlette/applications.py:64-81
Core Components
The Starlette Class
The Starlette class is the central entry point. It manages the application state, the middleware stack, and routing logic.
- debug: If
True, the application returns HTML tracebacks on 500 errors viaServerErrorMiddleware. - routes: A sequence of
BaseRouteobjects (Routes, Mounts, or Hosts). - middleware: A sequence of
Middlewareobjects to wrap the application. - lifespan: A context manager for startup and shutdown logic.
Sources: starlette/applications.py:23-50, starlette/middleware/errors.py:157-175
Routing
Routing is handled by the Router class, which matches incoming scopes to specific endpoints. Routes can be defined for HTTP or WebSockets.
| Route Type | Description |
|---|---|
Route | Matches HTTP paths to sync or async functions. |
WebSocketRoute | Matches WebSocket paths to async functions. |
Mount | Mounts another ASGI app or sub-router under a path prefix. |
Host | Routes requests based on the Host header. |
Sources: starlette/routing.py:448-644
Responses
Starlette provides several response classes that handle serialization and headers automatically.
from starlette.responses import PlainTextResponse, JSONResponse, RedirectResponse
# Simple text
resp = PlainTextResponse("Hello")
# JSON with automatic content-type
resp = JSONResponse({"data": 123})
# Redirection
resp = RedirectResponse(url="/new-path")
Sources: README.md:73-81, starlette/routing.py:27-31
Advanced Usage
Using Starlette as a Toolkit
You do not need to use the Starlette application class. You can use individual components as standalone ASGI applications.
from starlette.responses import PlainTextResponse
async def app(scope, receive, send):
assert scope['type'] == 'http'
response = PlainTextResponse('Hello, world!')
await response(scope, receive, send)
Sources: README.md:73-81
Middleware Stack Generation
The middleware stack is built when the application is first called. It wraps the router in layers of middleware based on the provided configuration.
Sources: starlette/applications.py:64-90
Startup and Shutdown (Lifespan)
Modern Starlette applications use the lifespan parameter to handle setup and teardown, replacing the deprecated on_startup and on_shutdown events.
@asynccontextmanager
async def lifespan(app):
# Startup logic
yield
# Shutdown logic
app = Starlette(lifespan=lifespan)
Sources: starlette/applications.py:48-51, starlette/routing.py:596-608
Summary
Starlette serves as a high-performance foundation for Python web development, offering both a structured framework and a modular toolkit. By combining Route definitions, Middleware stacks, and specialized Response types, developers can build scalable asynchronous services with minimal boilerplate.
Sources: README.md:16-30