CORS middleware helps your FastAPI app safely share resources with web pages from other websites. It controls who can access your API.
0
0
CORS middleware setup in FastAPI
Introduction
When your frontend app runs on a different domain or port than your FastAPI backend.
When you want to allow specific websites to call your API from browsers.
When you want to prevent unauthorized websites from accessing your API.
When building APIs that will be used by web apps hosted elsewhere.
When testing your API with frontend apps running locally on different ports.
Syntax
FastAPI
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=["GET", "POST"], allow_headers=["*"] )
allow_origins is a list of URLs allowed to access your API.
Use allow_methods to specify which HTTP methods are allowed.
Examples
This allows all websites to access your API (not recommended for production).
FastAPI
app.add_middleware(
CORSMiddleware,
allow_origins=["*"]
)Allows only a local frontend on port 3000 to access GET, POST, and PUT methods with specific headers.
FastAPI
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_methods=["GET", "POST", "PUT"],
allow_headers=["Content-Type"]
)Sample Program
This FastAPI app allows requests from localhost and a specific frontend domain. It enables all HTTP methods and headers. The endpoint returns a simple greeting message.
FastAPI
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "http://localhost", "http://localhost:3000", "https://myfrontend.com" ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"] ) @app.get("/hello") def hello(): return {"message": "Hello from FastAPI with CORS!"}
OutputSuccess
Important Notes
Setting allow_origins to ["*"] allows all websites but can be unsafe.
Always specify only the domains you trust to improve security.
Use browser DevTools Network tab to check CORS headers in responses.
Summary
CORS middleware controls which websites can access your FastAPI API.
Configure allow_origins, allow_methods, and allow_headers to set permissions.
Use it when your frontend and backend run on different domains or ports.