Bird
Raised Fist0
FastAPIframework~10 mins

CORS middleware setup in FastAPI - Step-by-Step Execution

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
Concept Flow - CORS middleware setup
Start FastAPI app
Import CORS middleware
Configure allowed origins, methods, headers
Add CORS middleware to app
Run app with CORS enabled
Browser sends request
Middleware checks origin
Allow request
Response sent with CORS headers
This flow shows how FastAPI sets up CORS middleware to check incoming requests' origins and allow or block them accordingly.
Execution Sample
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=["*"],
)
This code creates a FastAPI app and adds CORS middleware allowing only https://example.com to make GET and POST requests.
Execution Table
StepActionInput/StateMiddleware CheckResult
1Start appNo requests yetNo checkApp ready
2Add CORS middlewareallow_origins=['https://example.com']ConfiguredMiddleware active
3Incoming requestOrigin: https://example.com, Method: GETOrigin allowed?Allowed
4Send responseInclude CORS headersHeaders addedResponse sent with CORS headers
5Incoming requestOrigin: https://notallowed.com, Method: GETOrigin allowed?Blocked
6Send responseNo CORS headersRequest rejectedResponse sent without CORS headers
7Incoming requestOrigin: https://example.com, Method: DELETEMethod allowed?Blocked
8Send responseNo CORS headersRequest rejectedResponse sent without CORS headers
💡 Requests blocked if origin or method not allowed; otherwise, allowed with CORS headers.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5After Step 7
allow_origins[]["https://example.com"]["https://example.com"]["https://example.com"]["https://example.com"]
allow_methods[]["GET", "POST"]["GET", "POST"]["GET", "POST"]["GET", "POST"]
request_originNoneNone"https://example.com""https://notallowed.com""https://example.com"
request_methodNoneNone"GET""GET""DELETE"
request_allowedFalseFalseTrueFalseFalse
Key Moments - 3 Insights
Why does a request from https://notallowed.com get blocked even if the method is GET?
Because the middleware checks the origin first and blocks any origin not in allow_origins, as shown in execution_table step 5.
What happens if the request method is DELETE but the origin is allowed?
The middleware blocks the request because DELETE is not in allow_methods, as shown in execution_table step 7.
Why are CORS headers only added to some responses?
CORS headers are added only when the request passes origin and method checks, as seen in steps 4 and blocked in steps 6 and 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of request_allowed at step 3?
ATrue
BFalse
CNone
DError
💡 Hint
Check the 'request_allowed' column in variable_tracker after step 3.
At which step does the middleware block a request due to an unallowed origin?
AStep 3
BStep 5
CStep 7
DStep 4
💡 Hint
Look at execution_table rows where 'Result' is 'Blocked' and check the 'Input/State' for origin.
If you add 'DELETE' to allow_methods, which step's result would change?
AStep 3
BStep 5
CStep 7
DStep 8
💡 Hint
Check the step where method DELETE is blocked and see what would happen if it was allowed.
Concept Snapshot
FastAPI CORS middleware setup:
- Import CORSMiddleware
- Add middleware with app.add_middleware(CORSMiddleware, allow_origins=[...], allow_methods=[...], allow_headers=[...])
- Middleware checks each request's Origin and Method
- Allows requests matching config, blocks others
- Adds CORS headers only to allowed requests
Full Transcript
This visual execution shows how to set up CORS middleware in FastAPI. First, the app imports and adds CORSMiddleware with specific allowed origins and methods. When a request comes in, the middleware checks if the origin is in the allowed list and if the method is permitted. If both checks pass, the request is allowed and CORS headers are added to the response. Otherwise, the request is blocked and no CORS headers are sent. The variable tracker shows how request origin, method, and allowed status change step by step. Key moments clarify why some requests are blocked. The quiz tests understanding of these steps.

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