# 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. ## Install Save as a script file and run: ## Quick Use ```bash pip install starlette uvicorn ``` ```python from starlette.applications import Starlette from starlette.routing import Route from starlette.responses import JSONResponse import uvicorn async def list_assets(request): return JSONResponse([{"repo": "react", "stars": 230000}]) async def create_asset(request): data = await request.json() return JSONResponse(data, status_code=201) app = Starlette(routes=[ Route("/api/assets", list_assets, methods=["GET"]), Route("/api/assets", create_asset, methods=["POST"]), ]) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000) ``` ## Intro Starlette is a lightweight ASGI framework/toolkit for building async web services in Python. Created by Tom Christie (also creator of Django REST Framework), Starlette is the foundation that FastAPI is built on top of. It provides routing, middleware, WebSocket, GraphQL (via ariadne/strawberry), background tasks, streaming responses, and test client. - **Repo**: https://github.com/Kludex/starlette (originally encode/starlette) - **Stars**: 12K+ - **Language**: Python - **License**: BSD 3-Clause ## What Starlette Does - **ASGI** — fully async, works with uvicorn, hypercorn, daphne - **Routing** — path parameters, Mount for sub-apps - **Middleware** — CORS, GZip, HTTPS redirect, Trusted Host - **WebSocket** — native support - **Background tasks** — fire-and-forget after response - **Streaming** — StreamingResponse for large files - **Static files** — StaticFiles mount - **Test client** — httpx-based test client - **Event handlers** — startup/shutdown lifecycle ## Comparison | Framework | Level | Validation | |---|---|---| | Starlette | Low-level ASGI | Manual | | FastAPI | High-level (on Starlette) | Pydantic | | Litestar | High-level ASGI | msgspec/Pydantic | | Django | Full-stack WSGI/ASGI | Django forms | ## 常见问题 FAQ **Q: Starlette vs FastAPI?** A: FastAPI 就是 Starlette + Pydantic + OpenAPI 自动生成。需要更多控制或更轻量选 Starlette,需要自动文档和验证选 FastAPI。 ## 来源与致谢 Sources - Docs: https://www.starlette.io - GitHub: https://github.com/Kludex/starlette - License: BSD 3-Clause --- Source: https://tokrepo.com/en/workflows/41300507-3634-11f1-9bc6-00163e2b0d79 Author: Script Depot