-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample2.py
More file actions
74 lines (54 loc) · 2.53 KB
/
example2.py
File metadata and controls
74 lines (54 loc) · 2.53 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""
USAGE - The code is a Python program that creates an API using FastAPI. It includes various
endpoints to perform CRUD operations on an inventory. The inventory is a dictionary
that contains items identified by their unique IDs.
The program also uses Pydantic to define the structure of the items in the inventory.
The endpoints are used to retrieve, create, update, and delete items from the
inventory using the HTTP methods GET, POST, PUT, and DELETE. The program also
includes validations for parameters passed in the endpoint requests.
"""
from fastapi import FastAPI, Path, Query, HTTPException, status
from typing import Optional
from pydantic import BaseModel
app = FastAPI() # Creates api object
inventory = {}
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
@app.get("/get-item/{item_id}")
def get_item(item_id: int = Path(None, gt=0, description="The ID of the item you would like to view")) : # Uses the int forces the parameter being passed to be an integer otherwise it wont work
return inventory[item_id]
@app.get("/get-by-name")
def get_item(name: str = None):
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 # Updates the item in our inventory
if item.price != None:
inventory[item_id].price = item.price
if item.brand != None:
inventory[item_id].brand = item.brand
return inventory[item_id]
@app.delete("/delete-item")
def delete_item(item_id: int = Query(..., description="The 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"}