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)