Complete worked example
python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.testclient import TestClient
def inspect_example(request):
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["https://app.example.test"],
allow_credentials=False, allow_methods=["GET"], allow_headers=[])
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["testserver", "api.example.test"])
@app.get("/")
def read():
return {"ok": True}
with TestClient(app) as client:
response = client.get("/", headers={"Host": request.get("host", "testserver"),
"Origin": request.get("origin", "https://app.example.test")})
return {"status": response.status_code,
"body": response.json() if response.status_code == 200 else response.text,
"allow": response.headers.get("access-control-allow-origin")}- Reasoning
- A request with an allowed host reaches the endpoint. If its Origin matches the configured origin, the response includes the corresponding access-control-allow-origin value. A nonmatching origin can still receive an ordinary server response while lacking that browser permission header. The helper returns status, actual body and the allow-origin header. A host failure is plain text rather than the endpoint JSON, so the test handles each representation deliberately. There is no real DNS lookup or browser navigation; TestClient sends the synthetic headers in process.