|
| 1 | +from fastapi import FastAPI, HTTPException, status |
| 2 | +from pydantic import BaseModel, EmailStr |
| 3 | +from app.database import get_db_connection |
| 4 | +import psycopg2 |
| 5 | + |
| 6 | +app = FastAPI(title="QA Validator API") |
| 7 | + |
| 8 | +class CustomerCreate(BaseModel): |
| 9 | + name: str |
| 10 | + email: EmailStr |
| 11 | + |
| 12 | +class CustomerResponse(CustomerCreate): |
| 13 | + id: int |
| 14 | + status: str |
| 15 | + |
| 16 | +@app.post("/customers", response_model=CustomerResponse, status_code=status.HTTP_201_CREATED) |
| 17 | +def create_customer(customer: CustomerCreate): |
| 18 | + """Creates a new customer in the database.""" |
| 19 | + conn = get_db_connection() |
| 20 | + cur = conn.cursor() |
| 21 | + |
| 22 | + try: |
| 23 | + cur.execute( |
| 24 | + "INSERT INTO customers (name, email) VALUES (%s, %s) RETURNING id, name, email, status;", |
| 25 | + (customer.name, customer.email) |
| 26 | + ) |
| 27 | + new_customer = cur.fetchone() |
| 28 | + conn.commit() |
| 29 | + |
| 30 | + return CustomerResponse( |
| 31 | + id=new_customer[0], |
| 32 | + name=new_customer[1], |
| 33 | + email=new_customer[2], |
| 34 | + status=new_customer[3] |
| 35 | + ) |
| 36 | + except psycopg2.IntegrityError: |
| 37 | + conn.rollback() |
| 38 | + raise HTTPException(status_code=400, detail="Email already exists") |
| 39 | + finally: |
| 40 | + cur.close() |
| 41 | + conn.close() |
| 42 | + |
| 43 | +@app.get("/customers/{customer_id}", response_model=CustomerResponse) |
| 44 | +def get_customer(customer_id: int): |
| 45 | + """Retrieves a customer by ID.""" |
| 46 | + conn = get_db_connection() |
| 47 | + cur = conn.cursor() |
| 48 | + |
| 49 | + cur.execute("SELECT id, name, email, status FROM customers WHERE id = %s;", (customer_id,)) |
| 50 | + customer = cur.fetchone() |
| 51 | + cur.close() |
| 52 | + conn.close() |
| 53 | + |
| 54 | + if not customer: |
| 55 | + raise HTTPException(status_code=404, detail="Customer not found") |
| 56 | + |
| 57 | + return CustomerResponse(id=customer[0], name=customer[1], email=customer[2], status=customer[3]) |
0 commit comments