ryanpereira commited on
Commit
a866bd9
·
verified ·
1 Parent(s): 961c385

Create app.py

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