How to Enable and Configure CORS in FastAPI

How to Enable and Configure CORS in FastAPI

FastAPI and CORS: A Comprehensive Overview and Implementation Guide

How to enable CORS in FastAPI

CORS (Cross-Origin Resource Sharing) is a mechanism that allows web browsers to request resources from different origins (domains, protocols, or ports) than the one that the web page was loaded from. CORS is important for web applications that need to communicate with APIs hosted on different servers or domains.

FastAPI is a modern web framework for building APIs with Python. It is based on the Starlette framework and the Pydantic library and offers many features such as automatic documentation, validation, serialization, dependency injection, and more.

One of the features that FastAPI provides is a simple way to enable CORS for your API endpoints. In this article, we will see how to do that using the CORSMiddleware class.

What is CORSMiddleware?

CORSMiddleware is a class that implements the CORS protocol as a middleware component for Starlette and FastAPI applications. It allows you to configure various parameters for CORS, such as:

  • allow_origins: A list of origins (domains) that are allowed to access your API. You can use ["*"] it to allow all origins, but this is not recommended for security reasons.

  • allow_methods: A list of HTTP methods that are allowed for cross-origin requests. By default, it includes ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].

  • allow_headers: A list of HTTP headers that are allowed for cross-origin requests. By default, it includes ["*"], which means all headers are allowed.

  • allow_credentials: A boolean flag that indicates whether cookies and authorization headers are allowed for cross-origin requests. By default, it is set to False.

  • expose_headers: A list of HTTP headers that are exposed to the browser in the response. By default, it is an empty list.

  • max_age: An integer that specifies the maximum number of seconds that the browser can cache the preflight response. By default, it is set to 600.

How to use CORSMiddleware?

To use CORSMiddleware in your FastAPI application, you need to import it from fastapi.middleware.cors and add it to your app instance using the add_middleware method. For example:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
"http://localhost:3000",
"https://example.com",
]

app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

@app.get("/")
async def main():
    return {"message": "Hello World"}

Testing the CORS configuration

To test if your CORS configuration works as expected, send a request to your API from an origin that is specified in allowed origins ("localhost:3000", "example.com") and also make sure that origin is not the one hosting the API.

If you see the response from your app, it means that your CORS configuration is working. You can also inspect the response headers and see if they include the following:

  • Access-Control-Allow-Origin: the origin that sent the request, or * if all origins are allowed.

  • Access-Control-Allow-Credentials: true if credentials are allowed, or absent otherwise.

  • Access-Control-Allow-Methods: the methods that are allowed for the request, or * if all methods are allowed.

  • Access-Control-Allow-Headers: the headers that are allowed for the request, or * if all headers are allowed.

Conclusion

In this article, we learned how to enable CORS in FastAPI using the CORSMiddleware class. We saw how to configure various parameters for CORS, such as allowed origins, methods, headers, credentials, exposed headers, and max age. We also learned how to use regular expressions or wildcard patterns for the allow_origins parameter.

CORS is a useful feature for web applications that need to communicate with APIs hosted on different servers or domains. FastAPI makes it easy to enable and customize CORS for your API endpoints with just a few lines of code.

"The web is powerful because it's open. We should continue to embrace and extend it, not lock it down with unnecessary restrictions like same-origin policies." - Alex Russell, Google

Did you find this article valuable?

Support Sai Lokesh Reddy by becoming a sponsor. Any amount is appreciated!