Overview
Starlette 0.21, released on September 26, 2022, migrates TestClient from requests to httpx and improves typing.
Main Features
TestClient with httpx
The TestClient now uses httpx, offering HTTP/2 support and a native async API for testing.
python
from starlette.testclient import TestClient
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
async def api(request):
return JSONResponse({'status': 'ok'})
app = Starlette(routes=[Route('/api', api)])
# TestClient uses httpx internally
client = TestClient(app)
response = client.get('/api')
assert response.json() == {'status': 'ok'}
Improved typing
Type annotations are extended across main classes, making it easier to use with mypy and IDEs.
python
from starlette.requests import Request
from starlette.responses import Response, JSONResponse
# Types are well defined for mypy
async def handler(request: Request) -> Response:
data: dict = await request.json()
return JSONResponse({'received': data})
