How to fix CORS error in FastAPI Python

If you are developing an application and getting CORS error in Python FastAPI, then you can fix it by first importing the CORS middleware from FastAPI module. Then you need to add that middleware in your FastAPI “app” instance. Allow all origins, all credentials, and all methods and headers.

from fastapi import FastAPI

from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

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

It will fix CORS error in your Python FastAPI. Learn how to create a URL shortener app in Python.