liveBook · Manning

Access-Control-Allow headers

As explained in Build Financial Software with Generative AI (From Scratch)

Access-Control-Allow-Origin is an HTTP response header that specifies which origins may access a resource.

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

How Build Financial Software with Generative AI (From Scratch) covers it

How deep it goes
Defines the header and demonstrates server middleware configuration, while deferring broader CORS behavior beyond essential preflight handling.
Examples
Uses a localhost frontend calling a localhost health endpoint and configures FastAPI middleware for that origin.
What it assumes
Assumes familiarity with API calls, frontend origins, HTTP methods, and server configuration.
What you can do after
Operate/configure a FastAPI API to permit a specific frontend origin and required HTTP methods.
How it connects
Connects CORS with preflight requests, allowed methods, allowed headers, credentials, and least privilege.

Also explained in

Compare how 2 books explain Access-Control-Allow headers →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Financial Software with Generative AI (From Scratch). The section links point to the parts of the book it draws on.