Recall & Review
beginner
What does CORS stand for and why is it important in web development?
CORS stands for Cross-Origin Resource Sharing. It is important because it controls how resources on a web server can be requested from another domain, helping to keep web applications secure by preventing unauthorized cross-origin requests.
Click to reveal answer
beginner
How do you add CORS middleware in a FastAPI application?
You add CORS middleware by importing CORSMiddleware from fastapi.middleware.cors and then using app.add_middleware() with CORSMiddleware, specifying allowed origins, methods, headers, and optionally allow_credentials.
Click to reveal answer
beginner
What is the purpose of the 'allow_origins' parameter in FastAPI's CORSMiddleware?
'allow_origins' defines which domains are allowed to make cross-origin requests to your FastAPI app. It can be a list of URLs or ['*'] to allow all origins.
Click to reveal answer
intermediate
Why should you avoid setting 'allow_origins' to ['*'] in production?
Setting 'allow_origins' to ['*'] allows any website to access your API, which can be a security risk. It's better to specify trusted domains to limit access.
Click to reveal answer
beginner
Show a simple example of CORS middleware setup in FastAPI allowing only 'https://example.com'.
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=["*"],
allow_headers=["*"],
)
# This setup allows only https://example.com to access the API.Click to reveal answer
What does the 'allow_methods' parameter in FastAPI's CORSMiddleware control?
✗ Incorrect
'allow_methods' specifies which HTTP methods (GET, POST, etc.) are allowed in cross-origin requests.
Which FastAPI import is needed to add CORS middleware?
✗ Incorrect
CORSMiddleware is imported from fastapi.middleware.cors.
What happens if you set 'allow_origins' to ['*'] in CORSMiddleware?
✗ Incorrect
Setting 'allow_origins' to ['*'] means any domain can make cross-origin requests.
Which parameter allows cookies to be sent in cross-origin requests in FastAPI's CORSMiddleware?
✗ Incorrect
'allow_credentials=True' enables cookies and credentials in cross-origin requests.
Why is CORS middleware necessary in a FastAPI app?
✗ Incorrect
CORS middleware controls which external domains can access your API, enhancing security.
Explain how to set up CORS middleware in a FastAPI app to allow only specific domains.
Think about the parameters you pass to CORSMiddleware and how they control access.
You got /5 concepts.
Describe the security implications of using a wildcard '*' for allow_origins in CORS middleware.
Consider what happens when you open access to everyone.
You got /4 concepts.