Skip to content

Instantly share code, notes, and snippets.

@aalmazan
Created June 8, 2021 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aalmazan/4b47861f1f0126fc5f9987de474abc6b to your computer and use it in GitHub Desktop.
Save aalmazan/4b47861f1f0126fc5f9987de474abc6b to your computer and use it in GitHub Desktop.
Example FastAPI backend with CORS Middleware
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
app = FastAPI()
app.add_middleware(
# We add the middleware here
CORSMiddleware,
# These are the options we give the middleware and they map easily to their
# associated CORS headers
allow_origins=['http://localhost:63342', 'http://localhost'],
allow_methods=['GET', 'POST'],
allow_headers=['X-My-Custom-Header']
)
class Item(BaseModel):
name: str
@app.get('/')
async def root():
return dict(message="Hello")
@app.options('/items')
@app.get('/items')
async def list_items():
return [
Item(name="One"),
Item(name="Two"),
Item(name="Three"),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment