Repository navigation
Expand file tree
/
Copy pathdesignapi.py
More file actions
78 lines (46 loc) · 1.93 KB
/
Copy pathdesignapi.py
File metadata and controls
78 lines (46 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# how to initiate the server : uvicorn filename:app --reload
from fastapi import FastAPI, Path, Query, HTTPException, status
from typing import Optional, Annotated
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
brand: Optional[str] = None
class UpdateItem(BaseModel):
name: Optional[str] = None
price: Optional[float] = None
brand: Optional[str] = None
inventory = {}
@app.get("/get-item/{item_id}")
def get_item(item_id: int = Path(description= 'Enter the ID of the product you would like to get', gt=0)):
return inventory[item_id]
@app.get("/get-by-name/{item_id}")
def get_item(name: str = Query(None, title= 'Name', description= 'Name of item.', max_lenght= 10, min_lenght=2)):
for item_id in inventory:
if inventory[item_id].name == name:
return inventory[item_id]
raise HTTPException(status_code= 404, detail = 'Item name not found')
@app.post("/create-item/{item_id}")
def create_item(item_id: int, item: Item):
if item_id in inventory:
raise HTTPException(status_code= 400, detail = 'Item ID already exists.')
inventory[item_id]=item
return inventory[item_id]
@app.put("/update-item/{item_id}")
def update_item(item_id: int, item: UpdateItem):
if item_id not in inventory:
raise HTTPException(status_code= 404, detail = 'Item ID does not exist.')
if item.name != None:
inventory[item_id].name = item.name
if item.price != None:
inventory[item_id].price = item.price
if item.brand != None:
inventory[item_id].brand = item.brand
return {"Success": "Updated"}
@app.delete("/delete-item")
def delete_item(item_id: int = Query(..., description='ID of the item to delete', gt=0)):
if item_id not in inventory:
raise HTTPException(status_code= 404, detail = 'Item ID does not exist.')
del inventory[item_id]
return {'Success': 'Item Deleted!'}