File size: 1,686 Bytes
97f6a90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from pydantic import BaseModel
from fastapi import FastAPI, HTTPException
from typing import Optional,List
import uvicorn

app = FastAPI()
# 1. Define the blueprint/protocol/rules for communicating with the API
class Customer(BaseModel):
    name: str
    email: str
    phone: Optional[int] = None
    address: Optional[str] = None
    id: int

customer_list = []
# 2. Implement the logic for the API

# Create a customer
@app.post("/customers", response_model=Customer)
def create_customer(customer: Customer):
    customer_list.append(customer)
    return customer

# Read all customers
@app.get("/customers", response_model=List[Customer])
def get_customers():
    return customer_list
   

# Read a customer
#@app.get("/customer/{id}")
#def get_customer(id: int):
#    return {"result": customer_list[id]}

# Update a customer
@app.put("/customer/{id}", response_model=Customer)
def update_customer(id: int, updated_customer: Customer):
    for i,customer in enumerate(customer_list):
        if customer.id == id:
            customer_list[i] = updated_customer
            return updated_customer
    raise HTTPException(status_code=404, detail="Customer not found")

#delete a customer
@app.delete("/customer/{id}", response_model=Customer)
def delete_customer(id: int):
    for i,customer in enumerate(customer_list):
        if customer.id == id:
            deleted_customer = customer_list.pop(i)
            return deleted_customer
    raise HTTPException(status_code=404, detail="Customer not found")

@app.get("/")
def welcome():
    print("app running")
    return {"Welcome to the home page!"}

if __name__ == "__main__":
    uvicorn.run(app,host="0.0.0.0", port=7860)