-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyAPI.py
More file actions
107 lines (82 loc) · 2.09 KB
/
myAPI.py
File metadata and controls
107 lines (82 loc) · 2.09 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
from fastapi import FastAPI, Path
#for Post :
from pydantic import BaseModel
from typing import Optional
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={
1:{
"name":"Milk",
"price":3.99,
"brand":"Regular"
}
}
MSIT={
1:{
"Name":"Nevin Bali",
"SGPA":9.847
}
}
# First Api endpoint
@app.get("/")
def index():
return {"name": "First Data"}
# path Parameters
@app.get("/get-items/{item_id}")
def getItems(item_id : int):
return inventory[item_id]
#Self Practice :
@app.get("/Msit-items/{item_id}")
def getItems(item_id : int = Path( description="This is my first endpoint test")):
return MSIT[item_id]
#Query Parameters :
#http://127.0.0.1:8000/get-by-name?name=Milk
@app.get("/get-by-name")
def getName(name: str):
for item_Id in inventory:
if inventory[item_Id]["name"] == name:
return inventory[item_Id]
return {"Data": "Not Found"}
# @Types of Http Methods :
#Post :
@app.post("/create-item/{item_id}")
def createItem(*, item: Item, item_id: int):
if item_id in inventory:
return {"Error":"This Id already Existed"}
else:
#1st method : explicitly
inventory[item_id] = {
"name":item.name,
"price":item.price
}
#2nd method :
# inventory[item_id] = item
return inventory[item_id]
#Put :
@app.put("/update-item/{item_id}")
def update_Item(item_id:int, item:UpdateItem):
if item_id not in inventory:
return {"Error":"This Id doesn't 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 inventory[item_id]
#Delete :
@app.delete("/delete-item/{item_id}")
def deleteItem(item_id: int):
if item_id not in inventory:
return {"Error":"This Id doesn't Exist"}
del inventory[item_id]
return{
"Success":"Item Deleted Successfully"
}