Spaces:
Configuration error

colors99999 commited on
Commit
e6ace0e
·
verified ·
1 Parent(s): 5e885d2

Create app.py

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