from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["https://example.com"], allow_methods=["GET", "POST"], allow_headers=["X-Custom-Header"], ) @app.get("/") async def root(): return {"message": "Hello"}
The CORS middleware is configured to allow only requests from https://example.com origin. It permits only GET and POST methods and only the header X-Custom-Header. Other origins or methods will be blocked.
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # Add CORS middleware here
The allow_origins and allow_methods parameters both accept lists of strings. Using ["*"] for both allows all origins and all HTTP methods, respectively. This is the standard way recommended in the FastAPI documentation. Option B only allows the listed methods (not truly all), option B misses some common methods, and option B passes strings instead of lists, causing a type error.
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["https://allowed.com"], allow_methods=["GET", "POST"], allow_headers=["*"], allow_credentials=True ) @app.get("/") async def root(): return {"message": "Hello"}
The CORS middleware only allows requests from origins listed in allow_origins. If the frontend origin is not exactly https://allowed.com, the request is blocked. The other options are incorrect because ["*"] is valid for allow_headers, allow_credentials does not require allow_origins to be ["*"], and middleware order does not affect CORS behavior.
Setting allow_credentials=True allows the browser to send cookies, authorization headers, or TLS client certificates with cross-origin requests. This is necessary for authenticated requests across origins. It does not disable CORS or restrict protocols.
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["https://site1.com", "https://site2.com"], allow_methods=["GET", "POST"], allow_headers=["Content-Type", "Authorization"] ) @app.options("/") async def options(): return {"status": "ok"}
The Access-Control-Allow-Methods header lists allowed methods separated by commas and spaces. Since allow_methods is ["GET", "POST"], the header value will be "GET, POST". It is not joined without spaces or replaced by a wildcard.