FastAPI CORS (Env Config)

0.0.6 · active · verified Thu Apr 16

A lightweight Python library (version 0.0.6) that provides a simplified, environment variable-driven configuration for CORS settings in FastAPI applications. It acts as a wrapper around FastAPI's native `CORSMiddleware` (from Starlette), allowing developers to manage CORS policies such as allowed origins, methods, headers, and credentials through environment variables rather than direct code configuration.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `fastapi-cors` into a FastAPI application. The library automatically configures CORS based on environment variables like `CORS_ALLOW_ORIGINS`, `CORS_ALLOW_METHODS`, and `CORS_ALLOW_CREDENTIALS`. You simply instantiate the `CORS` class with your FastAPI app, and it applies the middleware based on the current environment settings.

import os
from fastapi import FastAPI
from fastapi_cors import CORS

# Example of setting environment variables (usually done in a .env file or deployment config)
# For local testing, you can uncomment these or use python-dotenv
os.environ['CORS_ALLOW_ORIGINS'] = 'http://localhost:3000,https://example.com'
os.environ['CORS_ALLOW_METHODS'] = 'GET,POST'
os.environ['CORS_ALLOW_CREDENTIALS'] = 'true'

app = FastAPI()

# Initialize fastapi-cors. It reads settings from environment variables automatically.
# You can pass include_health_check=False if not needed.
CORS(app)

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.post("/items/")
def create_item(item: dict):
    return {"item": item, "message": "Item created"}

# To run this app: uvicorn your_module_name:app --reload
# Make sure to set the environment variables before running.

view raw JSON →