Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
class Customer(BaseModel):
|
| 10 |
+
id: int
|
| 11 |
+
name: str
|
| 12 |
+
email: str
|
| 13 |
+
phone: Optional[str] = None
|
| 14 |
+
address: Optional[str] = None
|
| 15 |
+
|
| 16 |
+
# 2. Create the API endpoint
|
| 17 |
+
|
| 18 |
+
customers_list = []
|
| 19 |
+
#Create
|
| 20 |
+
@app.post("/customers", response_model=Customer)
|
| 21 |
+
def create_customer(customer: Customer):
|
| 22 |
+
customers_list.append(customer)
|
| 23 |
+
return customer
|
| 24 |
+
|
| 25 |
+
#Read
|
| 26 |
+
@app.get("/customers", response_model=List[Customer])
|
| 27 |
+
def get_customers():
|
| 28 |
+
return customers_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(customers_list):
|
| 34 |
+
if existing_customer.id == id:
|
| 35 |
+
customers_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(customers_list):
|
| 43 |
+
if customer.id == id:
|
| 44 |
+
deleted_customer = customers_list.pop(i)
|
| 45 |
+
return deleted_customer
|
| 46 |
+
raise HTTPException(status_code=404, detail="Customer not found")
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 50 |
+
|