47 lines
963 B
Python
47 lines
963 B
Python
from typing import Optional
|
|
|
|
from fastapi import FastAPI
|
|
from pydantic import BaseModel, Field
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
class Item(BaseModel):
|
|
id: Optional[int] = None
|
|
name: str = Field(description="The name of the item", regex="^[a-zA-Z0-9]*$")
|
|
price: float
|
|
is_offer: Optional[bool] = None
|
|
|
|
|
|
db = {
|
|
1: Item(id=1, name="Foo", price=19.99),
|
|
2: Item(id=2, name="Bar", price=29.99),
|
|
3: Item(id=3, name="Baz", price=39.99),
|
|
}
|
|
|
|
|
|
@app.get("/")
|
|
def get_items(
|
|
limit: int = 10,
|
|
offset: int = Field(0, description="db offset"),
|
|
q: Optional[str] = None,
|
|
):
|
|
print(limit, offset, q)
|
|
return [
|
|
{"item": db[k], "price": db[k].price}
|
|
for k in sorted(db.keys())[offset : offset + limit]
|
|
]
|
|
|
|
|
|
@app.get("/items/{item_id}")
|
|
def read_item(item_id: int):
|
|
return db[item_id]
|
|
|
|
|
|
@app.post("/items")
|
|
def create_item(item: Item) -> Item:
|
|
pid = list(db.keys())[-1] + 1
|
|
item.id = pid
|
|
db[pid] = item
|
|
return item
|