Skip to content

Items Path Operations

Code

main.py
from typing import Optional

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


class Item(BaseModel):
    title: str
    description: Optional[str] = None


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"}


@app.post("/users/{user_id}/items/")
def create_item_for_user(user_id: int, item: Item):
    return item


@app.get("/items/")
def read_items():
    return [
        {"title": "Portal Gun", "description": "A gun that shoots portals"},
        {"title": "Towel"},
    ]

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.