Bird
Raised Fist0
FastAPIframework~20 mins

CORS middleware setup in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
CORS Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the effect of this CORS middleware configuration?
Consider this FastAPI app snippet with CORS middleware added. What will be the behavior regarding cross-origin requests?
FastAPI
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"}
AOnly GET and POST requests from https://example.com with header X-Custom-Header are allowed cross-origin.
BAll origins can send any method requests with any headers cross-origin.
CNo cross-origin requests are allowed because allow_credentials is not set.
DOnly GET requests from any origin are allowed cross-origin.
Attempts:
2 left
💡 Hint
Look at the allow_origins, allow_methods, and allow_headers parameters.
📝 Syntax
intermediate
2:00remaining
Which option correctly adds CORS middleware allowing all origins and methods?
Select the correct code snippet to add CORS middleware in FastAPI that allows all origins and all HTTP methods.
FastAPI
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Add CORS middleware here
Aapp.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
Bapp.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"])
Capp.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET", "POST", "PUT", "DELETE"])
Dapp.add_middleware(CORSMiddleware, allow_origins="*", allow_methods="*")
Attempts:
2 left
💡 Hint
Check the types of allow_origins and allow_methods parameters and what values they accept.
🔧 Debug
advanced
2:00remaining
Why does this FastAPI app still block cross-origin requests despite adding CORS middleware?
Review the code and identify why cross-origin requests are blocked even though CORS middleware is added.
FastAPI
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"}
Aallow_credentials=True requires allow_origins to be set to ["*"] to work properly.
BThe allow_headers parameter set to ["*"] causes a syntax error, blocking requests.
CThe frontend is sending requests from a different origin than https://allowed.com, so they are blocked.
DThe middleware must be added after all route definitions to work.
Attempts:
2 left
💡 Hint
Check the origin of the requests compared to allow_origins list.
🧠 Conceptual
advanced
2:00remaining
What is the purpose of the allow_credentials parameter in FastAPI's CORS middleware?
Select the best explanation for what setting allow_credentials=True does in FastAPI's CORS middleware.
AIt automatically adds Access-Control-Allow-Origin: * header to all responses.
BIt disables all CORS protections and allows any cross-origin request.
CIt restricts cross-origin requests to only those using HTTPS protocol.
DIt allows cookies, authorization headers, or TLS client certificates to be included in cross-origin requests.
Attempts:
2 left
💡 Hint
Think about what credentials mean in web requests.
state_output
expert
2:00remaining
What is the value of the Access-Control-Allow-Methods header in this FastAPI response?
Given this FastAPI app with CORS middleware, what will be the exact value of the Access-Control-Allow-Methods header in the preflight OPTIONS response?
FastAPI
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"}
A"GET, POST"
B"GET,POST"
C"GET"
D"*"
Attempts:
2 left
💡 Hint
Check how FastAPI's CORS middleware formats the allow_methods header.

Practice

(1/5)
1. What is the main purpose of adding CORS middleware in a FastAPI application?
easy
A. To speed up the API response time
B. To control which external websites can access your API
C. To handle database connections securely
D. To log all incoming requests for debugging

Solution

  1. Step 1: Understand CORS middleware role

    CORS middleware is used to manage cross-origin requests, which means controlling which websites can call your API.
  2. Step 2: Identify the correct purpose

    Among the options, only controlling external website access matches the role of CORS middleware.
  3. Final Answer:

    To control which external websites can access your API -> Option B
  4. Quick Check:

    CORS controls access permissions [OK]
Hint: Remember: CORS = Cross-Origin Resource Sharing control [OK]
Common Mistakes:
  • Confusing CORS with performance optimization
  • Thinking CORS manages database security
  • Assuming CORS logs requests
2. Which of the following is the correct way to add CORS middleware in FastAPI?
easy
A. app.middleware(CORSMiddleware, allow_origins=["*"])
B. app.use(CORSMiddleware, allow_origins=["*"])
C. app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"])
D. app.add_cors(allow_origins=["*"])

Solution

  1. Step 1: Recall FastAPI middleware syntax

    FastAPI uses app.add_middleware() to add middleware components like CORSMiddleware.
  2. 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.
  3. Final Answer:

    app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"]) -> Option C
  4. Quick Check:

    Use add_middleware() to add CORS [OK]
Hint: FastAPI middleware always uses add_middleware() method [OK]
Common Mistakes:
  • Using app.use() which is not FastAPI syntax
  • Trying app.middleware() instead of add_middleware()
  • Calling a non-existent add_cors() method
3. Given this FastAPI code snippet, what will be the effect of the CORS middleware?
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"}
medium
A. Only requests from https://example.com with GET or POST methods are allowed
B. All origins and methods are allowed
C. No requests are allowed because allow_origins is too restrictive
D. Only GET requests from any origin are allowed

Solution

  1. 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.
  2. Step 2: Determine request permissions

    Requests from other origins or methods not in GET/POST will be blocked by CORS policy.
  3. Final Answer:

    Only requests from https://example.com with GET or POST methods are allowed -> Option A
  4. Quick Check:

    allow_origins and allow_methods restrict access [OK]
Hint: Check allow_origins and allow_methods lists carefully [OK]
Common Mistakes:
  • Assuming allow_origins=["*"] when it is not
  • Ignoring allow_methods restrictions
  • Thinking all origins are allowed by default
4. Identify the error in this FastAPI CORS middleware setup:
app.add_middleware(
    CORSMiddleware,
    allow_origins="*",
    allow_methods=["GET", "POST"],
    allow_headers=["*"]
)
medium
A. CORSMiddleware must be imported from fastapi.middleware.security
B. allow_methods should be a string, not a list
C. allow_headers cannot contain '*'
D. allow_origins should be a list, not a string

Solution

  1. Step 1: Check allow_origins type

    allow_origins must be a list of strings, but here it is a single string "*".
  2. Step 2: Verify other parameters

    allow_methods is correctly a list, allow_headers can accept ["*"] as a list.
  3. Final Answer:

    allow_origins should be a list, not a string -> Option D
  4. Quick Check:

    allow_origins requires a list [OK]
Hint: Always use a list for allow_origins, even if one item [OK]
Common Mistakes:
  • Passing allow_origins as a string instead of list
  • Misunderstanding allow_methods type
  • Wrong import path for CORSMiddleware
5. You want your FastAPI backend to accept requests from two frontend domains: https://app1.example.com and https://app2.example.com. You also want to allow all HTTP methods and headers. Which CORS middleware setup is correct?
hard
A. app.add_middleware(CORSMiddleware, allow_origins=["https://app1.example.com", "https://app2.example.com"], allow_methods=["*"], allow_headers=["*"])
B. app.add_middleware(CORSMiddleware, allow_origins=["*"])
C. app.add_middleware(CORSMiddleware, allow_origins=["https://app1.example.com", "https://app2.example.com"], allow_methods=["GET", "POST"], allow_headers=["Content-Type"])
D. app.add_middleware(CORSMiddleware, allow_origins="https://app1.example.com,https://app2.example.com", allow_methods=["*"], allow_headers=["*"])

Solution

  1. Step 1: Set allow_origins correctly

    To allow two specific domains, use a list with both URLs as strings.
  2. Step 2: Allow all methods and headers

    Using ["*"] for allow_methods and allow_headers allows all HTTP methods and headers.
  3. 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.
  4. Final Answer:

    app.add_middleware(CORSMiddleware, allow_origins=["https://app1.example.com", "https://app2.example.com"], allow_methods=["*"], allow_headers=["*"]) -> Option A
  5. Quick Check:

    List origins + wildcard methods/headers [OK]
Hint: Use list for origins and ["*"] to allow all methods/headers [OK]
Common Mistakes:
  • 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