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
CORS middleware setup
📖 Scenario: You are building a simple FastAPI web application that will be accessed from different websites. To allow these websites to communicate with your API safely, you need to set up CORS (Cross-Origin Resource Sharing) middleware.
🎯 Goal: Set up CORS middleware in a FastAPI app to allow requests from specific origins.
📋 What You'll Learn
Create a FastAPI app instance
Define a list of allowed origins
Add CORS middleware to the app with the allowed origins
Configure the middleware to allow all methods and headers
💡 Why This Matters
🌍 Real World
Many web APIs need to allow requests from web pages hosted on different domains. Setting up CORS middleware correctly lets your API communicate safely with these web clients.
💼 Career
Understanding and configuring CORS is essential for backend developers working with web APIs to ensure secure and functional cross-origin requests.
Progress0 / 4 steps
1
Create a FastAPI app instance
Import FastAPI from fastapi and create a variable called app that is an instance of FastAPI().
FastAPI
Hint
Use from fastapi import FastAPI and then app = FastAPI().
2
Define allowed origins list
Create a list called origins with these exact strings: "http://localhost" and "http://localhost:3000".
FastAPI
Hint
Make a list named origins with the two URLs as strings.
3
Add CORS middleware to the app
Import CORSMiddleware from fastapi.middleware.cors. Then add CORS middleware to app using app.add_middleware with these arguments: allow_origins=origins, allow_credentials=True, allow_methods=["*"], and allow_headers=["*"].
FastAPI
Hint
Use app.add_middleware with CORSMiddleware and set the parameters exactly as described.
4
Complete the FastAPI app with a root path
Add a root path operation to app using @app.get("/") that returns a dictionary with {"message": "Hello World"}.
FastAPI
Hint
Use @app.get("/") decorator and define an async function root that returns the dictionary.
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
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 B
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
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 C
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
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 D
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
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 A
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