upil / main.py
bagustyo's picture
Update main.py
37bb233 verified
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr
import random
import string
from datetime import datetime
import json
from pathlib import Path
# Define the app
app = FastAPI()
# File to store the JSON database
DB_FILE = Path("database.json")
# Ensure the JSON file exists
if not DB_FILE.exists():
DB_FILE.write_text(json.dumps([]))
# Data model
class Data(BaseModel):
number: int
email: EmailStr # Add the email field with validation
# Generate unique ID
def generate_id():
return ''.join(random.choices(string.ascii_letters + string.digits, k=8))
# Read database
def read_database():
with DB_FILE.open("r") as f:
return json.load(f)
# Write database
def write_database(data):
with DB_FILE.open("w") as f:
json.dump(data, f, indent=4)
# Endpoint to add data
@app.post("/add")
def add_data(data: Data):
database = read_database()
new_entry = {
"id": generate_id(),
"date": datetime.utcnow().isoformat(),
"number": data.number,
"email": data.email, # Include the email field
}
database.append(new_entry)
write_database(database)
return new_entry
# Endpoint to get all data
@app.get("/data")
def get_data():
return read_database()
@app.get("/data/{item_id}")
def get_data_by_id(item_id: str):
database = read_database()
for entry in database:
if entry["id"] == item_id:
return entry
raise HTTPException(status_code=404, detail="Item not found")