dipeshxc commited on
Commit
8192c2a
·
verified ·
1 Parent(s): 8602a9b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+ from pydantic import BaseModel
3
+ from fastapi import FastAPI, HTTPException
4
+ import uvicorn
5
+
6
+ app = FastAPI()
7
+
8
+ #1. define the blueprint for APIs
9
+
10
+ class Customers(BaseModel):
11
+
12
+ id: int
13
+ name: str
14
+ email: str
15
+ phone: Optional[str] = None
16
+ address: Optional[str] = None
17
+
18
+ #2. create the APIs endpoint
19
+
20
+ customers_list = []
21
+ # create
22
+ @app.post("/customers", response_model=Customers)
23
+ def create_customer(customer: Customers):
24
+ customers_list.append(customer)
25
+ return customer
26
+
27
+ # read
28
+
29
+ @app.get("/customers", response_model=List[Customers])
30
+ def get_customers():
31
+ return customers_list
32
+
33
+ # update
34
+ @app.put("/customers/{id}", response_model=Customers)
35
+ def update_customer(id: int, customer: Customers):
36
+ for i, existing_customer in enumerate(customers_list):
37
+ if existing_customer.id == id:
38
+ customers_list[i] = customer
39
+ return customer
40
+ raise HTTPException(status_code=404, detail="Customer not found")
41
+
42
+ # delete
43
+ @app.delete("/customers/{id}", response_model=Customers)
44
+ def delete_customer(id: int):
45
+ for i, existing_customer in enumerate(customers_list):
46
+ if existing_customer.id == id:
47
+ deleted_customer = customers_list.pop(i)
48
+ return deleted_customer
49
+ raise HTTPException(status_code=404, detail="Customer not found")
50
+
51
+ #3. run the app
52
+
53
+ if __name__ == "__main__":
54
+ uvicorn.run(app, host="0.0.0.0", port=7860)
55
+