Created
June 8, 2021 21:25
-
-
Save aalmazan/4b47861f1f0126fc5f9987de474abc6b to your computer and use it in GitHub Desktop.
Example FastAPI backend with CORS Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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