Skip to main content
The CORSMiddleware class allows you to configure Cross-Origin Resource Sharing (CORS) headers for your FastrAPI application. This is essential when your API needs to be accessed from web applications running on different domains.

Parameters

allow_origins
list[str]
default:"[]"
List of origins that are allowed to make cross-origin requests. Use ["*"] to allow all origins.
allow_origins=["https://example.com", "https://app.example.com"]
allow_methods
list[str]
default:"[\"GET\", \"POST\", \"PUT\", \"DELETE\"]"
HTTP methods that are allowed for cross-origin requests. Use ["*"] to allow all methods.
allow_methods=["GET", "POST", "OPTIONS"]
allow_headers
list[str]
default:"[]"
HTTP headers that are allowed in cross-origin requests. Use ["*"] to allow all headers.
allow_headers=["Content-Type", "Authorization"]
allow_credentials
bool
default:"false"
Whether to allow credentials (cookies, authorization headers) in cross-origin requests.
allow_credentials=True
expose_headers
list[str]
default:"[]"
HTTP headers that should be exposed to the browser in cross-origin responses.
expose_headers=["X-Request-ID", "X-Rate-Limit"]
max_age
int
default:"600"
Maximum number of seconds the browser should cache preflight request results.
max_age=3600  # 1 hour

Usage

from fastrapi import FastrAPI
from fastrapi.middleware import CORSMiddleware

app = FastrAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
    allow_credentials=False
)

Examples

Allow specific origins

app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "https://example.com",
        "https://app.example.com"
    ],
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["Content-Type", "Authorization"],
    allow_credentials=True
)

Allow all origins (development only)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"]
)

Build docs developers (and LLMs) love