How to Fix Python FastAPI CORS Error
In this tutorial, you'll learn about How to Fix Python FastAPI CORS Error. We cover key concepts, practical examples, and best practices.
FastAPI blocks cross-origin requests by default. A CORS error appears in the browser console when a frontend on a different origin tries to call your API.
The Wrong Way
from fastapi import FastAPI
app = FastAPI()
@app.get("/data")
def get_data():
return {"message": "hello"}
A browser frontend at http://localhost:3000 calling this API gets:
Access to fetch at 'http://localhost:8000/data' from origin 'http://localhost:3000' has been blocked by CORS policy
The Right Way
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/data")
def get_data():
return {"message": "hello"}
The request now succeeds with HTTP 200.
Prevention Tips
- Restrict
allow_originsto specific domains in production. - Never use
allow_origins=["*"]with credentials. - Add CORS middleware before route definitions.
- Test preflight
OPTIONSrequests with curl. - Use environment variables for allowed origins.
Common Mistakes with fastapi cors
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro