Cross-Origin Resource Sharing (CORS) is a browser security mechanism that lets a server control which external origins may access its resources. It becomes visible when a web page, such as a dashboard served from localhost:3000, calls an API at localhost:8000. Browsers may issue a preflight request before the actual request; missing or unsuitable response headers then block the call. section 3.4
Configure CORS narrowly, then broaden the policy only when the application requires it:
- Set Access-Control-Allow-Origin to the expected site, such as http://localhost:3000 or http://localhost:4000; avoid a wildcard unless it is genuinely appropriate. section 3.4 section 7.5.1
- Allow only the HTTP methods the application uses, such as GET during an initial health-check integration and GET plus POST for the MVP. section 3.4 section 7.5.1
- Configure allowed headers and credentials deliberately, remembering that framework versions may differ in whether OPTIONS must be listed for preflight requests. section 3.4 section 7.5.1
Allowing a local dashboard to call FastAPI
A FastAPI application can add CORSMiddleware with allow_origins=["http://localhost:3000"], allow_credentials=False, allow_methods=["GET"], and allow_headers=["*"]. For a later dashboard deployment, the origin can change to localhost:4000, credentials can be enabled, and GET and POST can be allowed. section 3.4 section 7.5.1
Listing 3.8 Incorporating CORS into our API
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware #1
import psycopg
DATABASE_URL = "dbname=postgres user=postgres
➥ password=secret host=postgres port=5432"
app = FastAPI()
origins = [ #2
"http://localhost:3000", #2
] #2
app.add_middleware( #3
CORSMiddleware, #3
allow_origins=origins, #3
allow_credentials=False, #3
allow_methods=["GET"], #3
allow_headers=["*"], #3
) #3
#3
def get_db():
conn = psycopg.connect(DATABASE_URL)
return conn
Inspect the complete FastAPI middleware configuration, including the origin list, credential setting, allowed methods, and allowed headers. section 3.4




