CORS middleware helps your FastAPI app safely share resources with web pages from other websites. It controls who can access your API.
CORS middleware setup in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["https://example.com"], allow_credentials=True, allow_methods=["GET", "POST"], allow_headers=["*"] )
allow_origins is a list of URLs allowed to access your API.
Use allow_methods to specify which HTTP methods are allowed.
app.add_middleware(
CORSMiddleware,
allow_origins=["*"]
)app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_methods=["GET", "POST", "PUT"],
allow_headers=["Content-Type"]
)This FastAPI app allows requests from localhost and a specific frontend domain. It enables all HTTP methods and headers. The endpoint returns a simple greeting message.
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "http://localhost", "http://localhost:3000", "https://myfrontend.com" ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"] ) @app.get("/hello") def hello(): return {"message": "Hello from FastAPI with CORS!"}
Setting allow_origins to ["*"] allows all websites but can be unsafe.
Always specify only the domains you trust to improve security.
Use browser DevTools Network tab to check CORS headers in responses.
CORS middleware controls which websites can access your FastAPI API.
Configure allow_origins, allow_methods, and allow_headers to set permissions.
Use it when your frontend and backend run on different domains or ports.
Practice
Solution
Step 1: Understand CORS middleware role
CORS middleware is used to manage cross-origin requests, which means controlling which websites can call your API.Step 2: Identify the correct purpose
Among the options, only controlling external website access matches the role of CORS middleware.Final Answer:
To control which external websites can access your API -> Option BQuick Check:
CORS controls access permissions [OK]
- Confusing CORS with performance optimization
- Thinking CORS manages database security
- Assuming CORS logs requests
Solution
Step 1: Recall FastAPI middleware syntax
FastAPI uses app.add_middleware() to add middleware components like CORSMiddleware.Step 2: Check option syntax correctness
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"]) uses app.add_middleware with CORSMiddleware and proper parameters, matching FastAPI docs.Final Answer:
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"]) -> Option CQuick Check:
Use add_middleware() to add CORS [OK]
- Using app.use() which is not FastAPI syntax
- Trying app.middleware() instead of add_middleware()
- Calling a non-existent add_cors() method
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=["*"],
)
@app.get("/")
async def root():
return {"message": "Hello"}Solution
Step 1: Analyze allow_origins and allow_methods
allow_origins is set to ["https://example.com"], so only that origin is allowed. allow_methods includes GET and POST.Step 2: Determine request permissions
Requests from other origins or methods not in GET/POST will be blocked by CORS policy.Final Answer:
Only requests from https://example.com with GET or POST methods are allowed -> Option AQuick Check:
allow_origins and allow_methods restrict access [OK]
- Assuming allow_origins=["*"] when it is not
- Ignoring allow_methods restrictions
- Thinking all origins are allowed by default
app.add_middleware(
CORSMiddleware,
allow_origins="*",
allow_methods=["GET", "POST"],
allow_headers=["*"]
)Solution
Step 1: Check allow_origins type
allow_origins must be a list of strings, but here it is a single string "*".Step 2: Verify other parameters
allow_methods is correctly a list, allow_headers can accept ["*"] as a list.Final Answer:
allow_origins should be a list, not a string -> Option DQuick Check:
allow_origins requires a list [OK]
- Passing allow_origins as a string instead of list
- Misunderstanding allow_methods type
- Wrong import path for CORSMiddleware
Solution
Step 1: Set allow_origins correctly
To allow two specific domains, use a list with both URLs as strings.Step 2: Allow all methods and headers
Using ["*"] for allow_methods and allow_headers allows all HTTP methods and headers.Step 3: Check for syntax correctness
app.add_middleware(CORSMiddleware, allow_origins=["https://app1.example.com", "https://app2.example.com"], allow_methods=["*"], allow_headers=["*"]) correctly uses a list for origins and lists with "*" for methods and headers.Final Answer:
app.add_middleware(CORSMiddleware, allow_origins=["https://app1.example.com", "https://app2.example.com"], allow_methods=["*"], allow_headers=["*"]) -> Option AQuick Check:
List origins + wildcard methods/headers [OK]
- Passing origins as a single comma string
- Using allow_methods with limited verbs instead of wildcard
- Setting allow_origins to ["*"] when only specific domains needed
