Registry / web-framework / fastapi-cors

fastapi-cors

JSON →
library0.0.6pypypi✓ verified 89d ago

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-cors
INSTALL
IMPORT
SIG · FASTAPI-CORS
F
fastapi-cors
web-frameworkpythonv0.0.6
Install
4.0s avg
Import
1164ms
Disk
31MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v0.0.6 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 1.216s · 32.9MB
glibc
py 3.10–3.920 runs
installs and imports cleanly · install 4.0s · import 1.113s · 33MB
31MB installed
● package 31MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

FastAPI
✓ from fastapi import FastAPI
CORS
✓ from fastapi_cors import CORS
✗ from fastapi.middleware.cors import CORSMiddleware
This library (fastapi-cors) provides its own wrapper `CORS` class, distinct from FastAPI's native `CORSMiddleware`.

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.
Debug
Known issues
gotchaDo not confuse `fastapi-cors.CORS` with `fastapi.middleware.cors.CORSMiddleware`. While `fastapi-cors` uses the latter internally, its API is different and relies on environment variables for configuration.
fix
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.
affects: All versions of fastapi-cors (0.0.x)
breakingUsing `allow_credentials=True` (set via `CORS_ALLOW_CREDENTIALS='true'`) with `allow_origins=['*']` (set via `CORS_ALLOW_ORIGINS='*'`) is a security violation according to the CORS specification and will be rejected by browsers.
fix
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'`).
affects: All versions
gotchaCORS middleware order is critical. The `CORS` instance (which adds the `CORSMiddleware`) must be added early in your FastAPI application's lifecycle, typically before any custom middleware or routers. Otherwise, some requests (especially those triggering exceptions) might bypass CORS headers.
fix
Ensure `CORS(app)` is called immediately after `app = FastAPI()` creation, before `app.include_router()` or other `app.add_middleware()` calls.
affects: All FastAPI versions
gotchaBrowser caching can cause persistent CORS errors even after fixing your backend configuration. The browser might have cached a preflight response indicating no access.
fix
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.
affects: All versions (browser-side issue)
Errors
Common errors & fixes
Access to fetch at 'http://localhost:8000/...' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The backend FastAPI application is not configured to allow requests from the origin 'http://localhost:3000' (or the specified frontend origin). This is the most common CORS error.
fix
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.
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
You are attempting to allow credentials (cookies, HTTP auth headers) from a frontend while simultaneously allowing requests from any origin (`*`), which is a security risk and forbidden by the CORS specification.
fix
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 `'*'`.
Failed to load resource: net::ERR_FAILED (or similar network error on OPTIONS request)
This often indicates a failed CORS 'preflight' request (an `OPTIONS` HTTP method request sent by the browser before the actual request). This can be due to disallowed methods, headers, or a general network/server issue.
fix
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.
Upgrade
Version history
0.0.6latest on PyPI · released Jul 12, 2023
Audit
Dependencies
fastapirequiredRequired for core application functionality, fastapi-cors is a wrapper for its middleware.
python-dotenvoptionalCommonly used to load environment variables for configuration.
Agent activity
29 hits · last 30 days
node
22
Amazon
1
OpenAI (training)
1
Resources
fastapi-cors — pip install fastapi-cors · libregistry