Spaces:
Configuration error
Configuration error
Download app.py from colors99999/enrollmentapi: direct link, hf CLI and curl.
- Browser
- Download file 2.46 kB
-
https://huggingface.co/spaces/colors99999/enrollmentapi/resolve/main/app.py
- Command line
-
hf download hf://spaces/colors99999/enrollmentapi/app.py
-
curl -L -o app.py https://huggingface.co/spaces/colors99999/enrollmentapi/resolve/main/app.py
2.46 kB
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel, field_validator | |
| from typing import List, Optional | |
| import re | |
| import uvicorn | |
| # 1. Initialize the API | |
| app = FastAPI() | |
| EMAIL_REGEX = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") | |
| # 2. Define the blueprint for APIs | |
| class Customer(BaseModel): | |
| id: int | |
| name: str | |
| email: str | |
| phone: Optional[str] = None | |
| address: Optional[str] = None | |
| def validate_email(cls, v: str) -> str: | |
| if not EMAIL_REGEX.match(v): | |
| raise ValueError("Invalid email format") | |
| return v | |
| # 3. Create a list of customers (starts empty) | |
| customer_list: List[Customer] = [] | |
| # Root - sanity check route so "/" doesn't 404 | |
| def read_root(): | |
| return {"message": "Customer API is running. Visit /docs for the interactive API docs."} | |
| # Create | |
| def create_customer(customer: Customer): | |
| if any(c.id == customer.id for c in customer_list): | |
| raise HTTPException(status_code=400, detail="Customer ID already exists") | |
| customer_list.append(customer) | |
| return customer | |
| # Read all | |
| def get_customers(): | |
| return customer_list | |
| # Read one | |
| def get_customer(customer_id: int): | |
| for customer in customer_list: | |
| if customer.id == customer_id: | |
| return customer | |
| raise HTTPException(status_code=404, detail="Customer not found") | |
| # Update | |
| def update_customer(customer_id: int, customer: Customer): | |
| for i, existing_customer in enumerate(customer_list): | |
| if existing_customer.id == customer_id: | |
| customer.id = customer_id # path id always wins, prevents id hijacking | |
| customer_list[i] = customer | |
| return customer | |
| raise HTTPException(status_code=404, detail="Customer not found") | |
| # Delete | |
| def delete_customer(customer_id: int): | |
| for i, customer in enumerate(customer_list): | |
| if customer.id == customer_id: | |
| deleted_customer = customer_list.pop(i) | |
| return deleted_customer | |
| raise HTTPException(status_code=404, detail="Customer not found") | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |