Skip to content

How to Fix Python FastAPI CORS Error

DodaTech Updated 2026-06-24 2 min read

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_origins to specific domains in production.
  • Never use allow_origins=["*"] with credentials.
  • Add CORS middleware before route definitions.
  • Test preflight OPTIONS requests with curl.
  • Use environment variables for allowed origins.

Common Mistakes with fastapi cors

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

### Why does my FastAPI app work in Postman but not the browser?

Postman does not enforce CORS policies. The browser blocks cross-origin requests unless the server sends the correct CORS headers. Always test CORS in a real browser.

What is a preflight request?

For non-simple requests (custom headers, non-standard methods), the browser sends an OPTIONS request first. FastAPI's CORSMiddleware handles this automatically if configured.

Should I use allow_origins=["*"] in development?

Only if you do not use credentials (cookies, authorization headers). With credentials, you must specify exact origins. Use allow_origins=["*"] cautiously even in development.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro