Starlette is a lightweight, high-performance ASGI (Asynchronous Server Gateway Interface) framework/toolkit, ideal for building asynchronous web applications and APIs in Python. It's designed to be a minimalist and powerful foundation, allowing developers to choose their preferred components for various tasks. Starlette embraces Python's `async`/`await` syntax, making it highly efficient for I/O-bound operations and concurrent requests.
Key features of Starlette include:
- ASGI Compatibility: Built upon the ASGI specification, enabling compatibility with various ASGI servers like Uvicorn and Hypercorn.
- Asynchronous Support: Full support for `async`/`await`, allowing for non-blocking operations and high concurrency.
- Routing: Powerful and flexible routing mechanisms, including path parameters, query parameters, and regular expression routes.
- WebSocket Support: Robust support for building real-time applications using WebSockets.
- Middleware: A clean and extensible middleware system for tasks like authentication, logging, CORS, and more.
- Dependency Injection: A sophisticated dependency injection system for managing application components.
- Test Client: A comprehensive `TestClient` for writing synchronous and asynchronous tests for your application.
- Exception Handling: Customizable exception handlers for graceful error management.
- GraphQL Support: Integrates well with GraphQL libraries.
- Session and Authentication: Provides primitives for building session management and authentication systems.
Starlette serves as the foundation for other popular frameworks like FastAPI, which builds upon Starlette by adding automatic data validation, serialization, and interactive API documentation (using Pydantic and OpenAPI). Its minimalist approach gives developers significant control and flexibility, making it an excellent choice for microservices, high-performance APIs, and custom web applications where fine-grained control over components is desired. Its performance and modern asynchronous architecture make it a compelling alternative to traditional WSGI frameworks for new projects.
Example Code
First, install Starlette and Uvicorn:
pip install starlette uvicorn
from starlette.applications import Starlette
from starlette.routing import Route, WebSocketRoute
from starlette.responses import JSONResponse, PlainTextResponse
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
import uvicorn
async def homepage(request):
"""Handles GET requests to the root path."""
return JSONResponse({'hello': 'world'})
async def user_detail(request):
"""Handles GET requests with a path parameter for user ID."""
user_id = request.path_params['user_id']
return JSONResponse({'user_id': user_id, 'message': f'Details for user {user_id}'})
async def search_items(request):
"""Handles GET requests with query parameters."""
query = request.query_params.get('q', 'no query provided')
limit = request.query_params.get('limit', '10')
return JSONResponse({'search_query': query, 'limit': limit, 'items': [f'item {i}' for i in range(int(limit))]})
async def websocket_endpoint(websocket):
"""Handles WebSocket connections."""
await websocket.accept()
await websocket.send_json({'message': 'Hello WebSocket!'})
while True:
message = await websocket.receive_text()
await websocket.send_text(f'Echo: {message}')
Define routes
routes = [
Route("/", homepage, methods=["GET"]),
Route("/users/{user_id:int}", user_detail, methods=["GET"]),
Route("/search", search_items, methods=["GET"]),
WebSocketRoute("/ws", websocket_endpoint),
]
Define middleware (optional)
middleware = [
Middleware(CORSMiddleware, allow_origins=["-"]),
]
Create the Starlette application
app = Starlette(routes=routes, middleware=middleware)
To run this application:
Save the code as 'main.py'
Open your terminal in the same directory and run: uvicorn main:app --reload
Then navigate to:
- http://127.0.0.1:8000/
- http://127.0.0.1:8000/users/123
- http://127.0.0.1:8000/search?q=starlette&limit=5
- Open browser console and try:
const ws = new WebSocket("ws://127.0.0.1:8000/ws");
ws.onmessage = (event) => console.log(event.data);
ws.onopen = () => ws.send("Hello from client!");








Starlette