Access-Control-Allow-Origin is an HTTP response header that tells a server which external origins may access a resource. It commonly resolves CORS errors when a frontend calls an API from a different origin. section 3.4
Configure the header narrowly alongside related CORS controls:
- Allow a focused origin, such as http://localhost:3000, instead of using the wildcard * unless broader access is necessary. section 3.4
- Permit only the HTTP methods currently required; the example uses GET. section 3.4
- Enable credentials only when authenticated requests, cookies, or other sensitive request state require them. section 3.4
FastAPI configuration
Register CORSMiddleware with allow_origins=["http://localhost:3000"], allow_methods=["GET"], and allow_credentials=False. This lets the local frontend call the API while keeping the origin and method scope limited. section 3.4
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 and related CORS settings. section 3.4

