How to enable cors in fastapi?

Member

by deron , in category: Javascript , 21 days ago

How to enable cors in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 20 days ago

@deron 

To enable Cross-Origin Resource Sharing (CORS) in FastAPI, you can use the fastapi.middleware.CORSMiddleware middleware. Here is an example of how to enable CORS in FastAPI:

  1. Install the required dependencies:
1
pip install fastapi uvicorn


  1. Create a FastAPI application and configure the CORS middleware:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Configure allowed origins, methods, and headers
origins = [
    "http://localhost",
    "http://localhost:8080",
]

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


In this example, we have configured CORS to allow requests from http://localhost and http://localhost:8080, with credentials allowed, and specifying the allowed methods and headers.

  1. Run the FastAPI application using Uvicorn:
1
uvicorn main:app --reload


With these steps, you should now have enabled CORS in your FastAPI application. You can customize the CORS settings according to your requirements.