
FastAPI
Learn essential concepts of cors in FastAPI.
This section covers CORS fundamentals, including:
CORS enables browser-based clients to make cross-origin requests to your API. Without proper CORS configuration, browsers block requests from different origins for security reasons.
Understanding CORS helps you:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# Simple CORS configuration
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"], # Frontend origin
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["*"],
)
@app.get("/api/data")
async def get_data():
return {"message": "Data from API"}# Allow multiple specific origins
origins = [
"http://localhost:3000",
"http://localhost:8080",
"https://example.com",
"https://app.example.com",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH"],
allow_headers=["Content-Type", "Authorization"],
max_age=600, # Cache pre-flight requests for 600 seconds
)# Development: Allow any origin (NOT for production)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Unsafe for production
allow_methods=["*"],
allow_headers=["*"],
)
# Production: Always specify exact origins
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"],
allow_credentials=True, # Only with specific origins
)CORS is critical for:
Next step: Explore the advanced section for production patterns and optimization techniques.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward