Cross - Origin Resource Sharing (CORS) is an HTTP - header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. When a browser makes a cross - origin request (a request to a different origin than the one serving the current page), it enforces the same - origin policy by default, which restricts such requests for security reasons. CORS provides a way to relax these restrictions in a controlled manner.
If you are building a FastAPI application that serves as an API and is consumed by a front - end application running on a different domain, browser security mechanisms will block the requests unless CORS is properly configured. For example, if your FastAPI API is running on http://api.example.com
and your front - end is on http://app.example.com
, without CORS support, the browser will prevent the front - end from making requests to the API.
First, make sure you have FastAPI and Uvicorn (a server for running FastAPI applications) installed. If not, you can install them using pip
:
pip install fastapi uvicorn
Here is a simple example of adding CORS support to a FastAPI application:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# List of allowed origins
origins = [
"http://localhost:3000", # Example: a local React app
]
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
return {"Hello": "World"}
To run the application, save the above code in a file named main.py
and run the following command in the terminal:
uvicorn main:app --reload
The allow_origins
parameter in the CORSMiddleware
is a list of origins that are allowed to make cross - origin requests to your FastAPI application. You should be as specific as possible when defining the allowed origins. For example, instead of using ["*"]
(which allows all origins), you can list only the domains that your application expects to receive requests from:
origins = [
"http://example.com",
"https://example.com",
"http://subdomain.example.com"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
# Other parameters...
)
The allow_methods
parameter specifies which HTTP methods are allowed in cross - origin requests. You can list specific methods like ["GET", "POST", "PUT", "DELETE"]
or use "*"
to allow all methods. Similarly, the allow_headers
parameter defines which headers are allowed in cross - origin requests. You can use "*"
to allow all headers, but in a production environment, it’s better to list only the necessary headers:
app.add_middleware(
CORSMiddleware,
# Other parameters...
allow_methods=["GET", "POST"],
allow_headers=["Content-Type", "Authorization"]
)
["*"]
for allow_origins
in production. This can expose your API to potential security risks, such as cross - site scripting (XSS) attacks.GET
and POST
requests, don’t allow other methods like PUT
or DELETE
unless they are actually needed.pytest
to send cross - origin requests and verify the responses.Adding CORS support to your FastAPI application is essential when you need to allow cross - origin requests. By following the concepts, usage methods, common practices, and best practices outlined in this blog post, you can ensure that your API is accessible to the intended front - end applications while maintaining a high level of security. Remember to be specific with your CORS configuration, test thoroughly, and follow web security best practices.