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.
pip install fastapi-corsVerified import paths — ran on the pinned version, not inferred.
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.
Use `from fastapi_cors import CORS` and configure via environment variables (e.g., `CORS_ALLOW_ORIGINS`). If you prefer direct code configuration, use `from fastapi.middleware.cors import CORSMiddleware` instead.
When `CORS_ALLOW_CREDENTIALS` is 'true', `CORS_ALLOW_ORIGINS` must list specific origins, not `*` (e.g., `CORS_ALLOW_ORIGINS='http://localhost:3000,https://app.example.com'`).
Ensure `CORS(app)` is called immediately after `app = FastAPI()` creation, before `app.include_router()` or other `app.add_middleware()` calls.
After making CORS changes, clear your browser's cache, use an incognito/private browsing window, or use a tool like `curl` or Postman to test the API directly.
Ensure the `CORS_ALLOW_ORIGINS` environment variable (or equivalent if `fastapi-cors` isn't used) correctly includes the exact origin of your frontend (e.g., `CORS_ALLOW_ORIGINS='http://localhost:3000'` ). Remember to restart your FastAPI application after changing environment variables.
If `CORS_ALLOW_CREDENTIALS` is set to 'true', then `CORS_ALLOW_ORIGINS` must be a comma-separated list of specific origins (e.g., `'http://localhost:3000,https://app.yourdomain.com'`). Do not use `'*'`.
Check that `CORS_ALLOW_METHODS` includes the method being used (e.g., `POST`, `PUT`) and `CORS_ALLOW_HEADERS` includes any custom headers being sent. Also, ensure the FastAPI app is running and accessible.