Starlette — The Little ASGI Framework That Shines
Starlette is a lightweight ASGI framework for building async web services in Python. It is the foundation that FastAPI is built on top of. Provides routing, middleware, WebSocket, GraphQL, background tasks, and streaming responses.
What it is
Starlette is a lightweight ASGI framework for building high-performance async web services in Python. It provides routing, middleware, WebSocket support, GraphQL, background tasks, and streaming responses. Most notably, Starlette is the foundation that FastAPI is built on top of, handling all the HTTP-level concerns while FastAPI adds data validation and OpenAPI generation.
Starlette targets Python developers who want async web capabilities without the overhead of a full framework. It is also relevant to anyone using FastAPI who wants to understand or extend the underlying request handling layer.
How it saves time or tokens
Starlette's minimal surface area means less boilerplate to write and maintain. A working API endpoint requires only a route function and a response object. The async-first design handles concurrent requests efficiently without thread pool management. For AI agent backends that need to handle streaming LLM responses, Starlette's native StreamingResponse maps directly to server-sent events without additional dependencies.
How to use
- Install Starlette and an ASGI server:
pip install starlette uvicorn
- Create a basic application:
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.responses import JSONResponse
import uvicorn
async def list_items(request):
return JSONResponse([{'name': 'item-1', 'status': 'active'}])
app = Starlette(routes=[Route('/items', list_items)])
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=8000)
- Run the server with
python app.pyand accesshttp://localhost:8000/items.
Example
Streaming response for an AI agent backend:
from starlette.responses import StreamingResponse
import asyncio
async def stream_response(request):
async def generate():
for i in range(10):
yield f'data: chunk {i}\n\n'
await asyncio.sleep(0.1)
yield 'data: [DONE]\n\n'
return StreamingResponse(
generate(),
media_type='text/event-stream'
)
This pattern is commonly used for streaming LLM completions to frontend clients via server-sent events.
Related on TokRepo
- AI Tools for API — API frameworks and tools for building AI service backends
- AI Tools for Coding — Development tools that complement web framework work
Common pitfalls
- Starlette requires an ASGI server like Uvicorn or Hypercorn. It does not include a built-in server, so forgetting to install one causes import errors at startup.
- WebSocket handlers must explicitly accept the connection before sending messages. Skipping
await websocket.accept()causes silent connection drops. - Middleware ordering matters. Authentication middleware must come before route-specific middleware to prevent unauthenticated access to protected endpoints.
- Always check the official documentation for the latest version-specific changes and migration guides before upgrading in production environments.
- For team deployments, establish clear guidelines on configuration and usage patterns to ensure consistency across developers.
Frequently Asked Questions
FastAPI is built on top of Starlette. Starlette handles HTTP routing, middleware, WebSocket, and responses. FastAPI adds Pydantic data validation, automatic OpenAPI documentation, and dependency injection on top of Starlette's foundation.
Yes. Starlette is one of the fastest Python web frameworks in benchmarks. Its async-first design handles thousands of concurrent connections efficiently. Combined with Uvicorn, it serves as a production-grade ASGI stack.
Yes. Starlette has built-in WebSocket support with a clean async interface. You define WebSocket routes alongside HTTP routes and use the WebSocket object to accept connections, send messages, and receive data.
Use Starlette when you want minimal overhead and do not need automatic data validation or OpenAPI docs. Starlette is ideal for lightweight services, proxies, streaming endpoints, or WebSocket servers where FastAPI's extras add unnecessary complexity.
Yes. Since FastAPI is built on Starlette, all Starlette middleware works directly with FastAPI applications. You can add CORS, authentication, and custom middleware using the same Starlette patterns.
Citations (3)
- Starlette GitHub— Starlette is a lightweight ASGI framework for Python
- FastAPI Documentation— Starlette is the foundation FastAPI is built on
- ASGI Spec— ASGI specification for async Python web applications
Related on TokRepo
Discussion
Related Assets
Moodle — Open-Source Learning Management System
The most widely used open-source learning platform, providing course management, assessments, and collaboration tools for educators and organizations worldwide.
Sylius — Headless E-Commerce Framework on Symfony
An open-source headless e-commerce platform built on Symfony and API Platform, designed for developers who need a customizable and API-first commerce solution.
Akaunting — Free Self-Hosted Accounting Software
A free, open-source online accounting application built on Laravel for small businesses and freelancers to manage invoices, expenses, and financial reports.