Skip to content

CORS - Cross Origin Resource Sharing

Code

main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel


class User(BaseModel):
    username: str


app = FastAPI()

origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost",
    "http://localhost:8080",
    "https://fastapiworkshop.yaquelinehoyos.com",
]

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


@app.post("/users/")
def create_user(user: User):
    return user


@app.get("/users/")
def read_users():
    return [{"username": "Rick"}, {"username": "Morty"}]


@app.get("/users/{user_id}")
def read_user(user_id: int):
    return {"id": user_id, "username": "Pickle Rick"}

Server

Run the live server:

$ uvicorn main:app --reload

<span style="color: green;">INFO</span>:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
<span style="color: green;">INFO</span>:     Started reloader process [28720]
<span style="color: green;">INFO</span>:     Started server process [28722]
<span style="color: green;">INFO</span>:     Waiting for application startup.
<span style="color: green;">INFO</span>:     Application startup complete.

API docs

Now you can open the API docs UI at: http://127.0.0.1:8000/docs.

Admin Dashboard

You can go to the admin dashboard (created for this workshop) to interact with your API: https://fastapiworkshop.yaquelinehoyos.com.

Info

This admin dashboard was created in a day for this workshop by @yaquelinehoyos. 🤓

Thanks Yaque! 🙇