lightbulbBook reference: Beyond the books. Original notes kept below; rewrite them in your own words.
2.2.1 Starlette
Starlette is a lightweight ASGI web framework for Python.
A useful way to think about it:
FastAPI
↓
Starlette
↓
ASGI
↓
Uvicorn
What does Starlette provide?
FastAPI is built on top of Starlette and uses Starlette for:
- Routing
- Requests and Responses
- Middleware
- WebSockets
- Background tasks
- Event loop integration
- ASGI support
For example, when you write:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def home():
return {"message": "Hello"}
Behind the scenes:
FastAPIextends Starlette.- The route handling comes from Starlette.
- Uvicorn runs the application.
Starlette Without FastAPI
You can use Starlette directly:
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
async def home(request):
return JSONResponse({"message": "Hello"})
app = Starlette(routes=[
Route("/", home)
])
This works, but you lose FastAPI features such as:
- Pydantic validation
- Automatic OpenAPI docs
- Dependency Injection (
Depends) - Request/response models
Why FastAPI Exists
Starlette gives you the web framework basics.
FastAPI adds:
Starlette
+ Pydantic validation
+ OpenAPI/Swagger docs
+ Dependency Injection
+ Better developer experience
= FastAPI
In Your FastAPI Projects
When you use:
from fastapi.middleware.cors import CORSMiddleware
or
from fastapi import Request
many of those components ultimately come from Starlette.
For backend interviews, a good one-line answer is:
lightbulbStarlette is the ASGI framework underneath FastAPI. It provides routing, middleware, request/response handling, WebSockets, and async support, while FastAPI builds on it by adding validation, dependency injection, and automatic API documentation.