CORS Headers

Add CORS middleware so browsers can call your API from a different domain

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

The same-origin policy

Browsers enforce a security rule called the same-origin policy. If a web page at https://myapp.com tries to call your API at https://api.myapp.com, the browser blocks the request. The two URLs have different origins (different subdomains count as different origins).

This protects users from malicious websites that try to make requests to other services on their behalf. But it also blocks legitimate requests — like your own frontend calling your own API.

CORS: Cross-Origin Resource Sharing

CORS is a set of HTTP headers that tells the browser which origins are allowed to call your API. When the browser sees these headers in the response, it allows the request to go through.

The key headers are:

  • Access-Control-Allow-Origin: which domains can make requests
  • Access-Control-Allow-Methods: which HTTP methods are allowed (GET, POST, etc.)
  • Access-Control-Allow-Headers: which request headers are allowed

FastAPI's CORSMiddleware

FastAPI includes a built-in CORSMiddleware that adds these headers to every response. You import it, configure the allowed origins, methods, and headers, and add it to your app. FastAPI handles the rest.

Using allow_origins=["*"] allows any domain to call your API. This is fine for development and public APIs. For production, replace "*" with specific domain names.

Instructions

Add CORS middleware to your API.

  1. Add from fastapi.middleware.cors import CORSMiddleware to the imports.
  2. After the app = FastAPI() line, call app.add_middleware() with these four arguments:
    • CORSMiddleware — the middleware class to register
    • allow_origins=["*"] — which domains can call your API ("*" means any domain)
    • allow_methods=["*"] — which HTTP methods are allowed (GET, POST, DELETE, etc.)
    • allow_headers=["*"] — which request headers the browser can send