FastAPI CORS Tutorial: How to Enable Cross-Origin Resource Sharing in Python

Posted by


In this tutorial, we will be focusing on Cross-Origin Resource Sharing (CORS) in FastAPI using Python. CORS allows a server to specify who can access its resources. This is important in preventing malicious scripts from accessing sensitive data on your server.

FastAPI provides built-in support for CORS through the use of the fastapi.middleware.cors module. We will demonstrate how to enable CORS in your FastAPI application and specify which origins are allowed to access your resources.

Step 1: Install FastAPI and Uvicorn
First, you need to have FastAPI and Uvicorn installed in your Python environment. You can install them using pip:

pip install fastapi uvicorn

Step 2: Create a FastAPI application
Next, create a new Python file for your FastAPI application. Let’s name it app.py. Here’s a simple FastAPI application to get started:

from fastapi import FastAPI

app = FastAPI()

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

Step 3: Enable CORS in your FastAPI application
To enable CORS in your FastAPI application, you need to import the CORSMiddleware class from the fastapi.middleware.cors module. Add the following code to your app.py file:

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

app = FastAPI()

# Specify the origins that are allowed to access your resources
origins = [
    "http://localhost",
    "http://localhost:3000",
    "https://example.com",
]

# Enable CORS in your FastAPI application
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
)

In the code above, we specified a list of origins that are allowed to access our resources. You can add as many origins as needed. Additionally, we enabled credentials, specified which HTTP methods are allowed, and allowed all headers. Adjust these settings based on your application’s requirements.

Step 4: Run your FastAPI application
Now you can run your FastAPI application using Uvicorn. Open a terminal window and run the following command:

uvicorn app:app --reload

Your FastAPI application should now be running, and CORS is enabled to allow access from the specified origins. You can test it by sending a request from a different origin and verify that the response includes the necessary CORS headers.

Congratulations! You have successfully enabled CORS in your FastAPI application using Python. CORS is an essential security feature that helps protect your server from unauthorized access. You can now build secure APIs with FastAPI and ensure that only trusted origins can access your resources.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x