Spaces:
Sleeping
Sleeping
| from pydantic import BaseModel | |
| from fastapi import FastAPI, HTTPException | |
| from typing import Optional | |
| import uvicorn | |
| app= FastAPI() | |
| # 1. Define the blueprint for APIs | |
| class Customer(BaseModel): | |
| id:int | |
| name: str | |
| email: str | |
| phone: Optional[str] = None | |
| address: Optional[str] = None | |
| # Initialize customer list | |
| customer_list = [] | |
| # 2. Create the api endpoint | |
| #Create | |
| def create_customer(customer:Customer): | |
| customer_list.append(customer) | |
| return customer | |
| #Read | |
| def get_customers(): | |
| return customer_list | |
| #Update | |
| def update_customer(id: int, customer: Customer): | |
| for i, existing_customer in enumerate(customer_list): | |
| if existing_customer.id == id: | |
| customer_list[i] = customer | |
| return customer | |
| raise HTTPException (status_code=404, detail ="Customer not found") | |
| #Delete | |
| def delete_customer(id: int): | |
| for i, customer in enumerate(customer_list): | |
| if customer.id == id: | |
| removed_customer = customer_list.pop(i) | |
| return removed_customer | |
| raise HTTPException(status_code=404, detail="Customer not found") | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |