feat: Generated endpoint endpoints/create-fruit.post.py via AI for Fruit

This commit is contained in:
Backend IM Bot 2025-04-14 15:43:55 +00:00
parent b442b03232
commit 81fae9acc2
5 changed files with 168 additions and 0 deletions

View File

@ -0,0 +1,28 @@
"""Initial creation of fruits table
Revision ID: 1a2b3c4d5e6f
Revises: 0001
Create Date: 2024-01-20 10:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1a2b3c4d5e6f'
down_revision = '0001'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'fruits',
sa.Column('id', sa.String(36), primary_key=True),
sa.Column('name', sa.String(), nullable=False),
sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),
sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),
)
op.create_index(op.f('ix_fruits_name'), 'fruits', ['name'], unique=True)
def downgrade():
op.drop_index(op.f('ix_fruits_name'), table_name='fruits')
op.drop_table('fruits')

View File

@ -0,0 +1,21 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from core.database import get_db
from schemas.fruit import FruitCreate, FruitSchema
from helpers.fruit_helpers import create_fruit, validate_fruit_name, format_fruit_response
router = APIRouter()
@router.post("/create-fruit", status_code=status.HTTP_201_CREATED, response_model=FruitSchema)
async def create_new_fruit(
fruit: FruitCreate,
db: Session = Depends(get_db)
):
if not validate_fruit_name(fruit.name):
raise HTTPException(status_code=400, detail="Invalid fruit name")
new_fruit = create_fruit(db=db, fruit_data=fruit)
if not new_fruit:
raise HTTPException(status_code=400, detail="Could not create fruit")
return format_fruit_response(new_fruit)

77
helpers/fruit_helpers.py Normal file
View File

@ -0,0 +1,77 @@
from typing import Optional
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from models.fruit import Fruit
from schemas.fruit import FruitCreate, FruitSchema
def create_fruit(db: Session, fruit_data: FruitCreate) -> Optional[Fruit]:
"""
Creates a new fruit in the database.
Args:
db (Session): The database session.
fruit_data (FruitCreate): The data for the fruit to create.
Returns:
Optional[Fruit]: The newly created fruit object, or None if creation fails.
"""
try:
db_fruit = Fruit(name=fruit_data.name)
db.add(db_fruit)
db.commit()
db.refresh(db_fruit)
return db_fruit
except IntegrityError:
db.rollback()
return None
def get_fruit_by_name(db: Session, name: str) -> Optional[Fruit]:
"""
Retrieves a fruit by its name.
Args:
db (Session): The database session.
name (str): The name of the fruit to retrieve.
Returns:
Optional[Fruit]: The fruit object if found, otherwise None.
"""
return db.query(Fruit).filter(Fruit.name == name).first()
def validate_fruit_name(name: str) -> bool:
"""
Validates the fruit name according to business rules.
Args:
name (str): The fruit name to validate.
Returns:
bool: True if the name is valid, False otherwise.
"""
if not name or not isinstance(name, str):
return False
# Remove whitespace and check length
cleaned_name = name.strip()
if len(cleaned_name) < 1:
return False
# Additional validation rules could be added here
return True
def format_fruit_response(fruit: Fruit) -> FruitSchema:
"""
Formats a fruit database object into a response schema.
Args:
fruit (Fruit): The fruit database object to format.
Returns:
FruitSchema: The formatted fruit response.
"""
return FruitSchema(
id=fruit.id,
name=fruit.name,
created_at=fruit.created_at,
updated_at=fruit.updated_at
)

13
models/fruit.py Normal file
View File

@ -0,0 +1,13 @@
from sqlalchemy import Column, String, DateTime
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from core.database import Base
import uuid
class Fruit(Base):
__tablename__ = "fruits"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = Column(String, unique=True, nullable=False, index=True)
created_at = Column(DateTime, default=func.now())
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

29
schemas/fruit.py Normal file
View File

@ -0,0 +1,29 @@
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
from uuid import UUID
class FruitBase(BaseModel):
name: str = Field(..., min_length=1, description="Fruit name")
class FruitCreate(FruitBase):
pass
class FruitUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1, description="Fruit name")
class FruitSchema(FruitBase):
id: UUID
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True
schema_extra = {
"example": {
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"name": "Apple",
"created_at": "2023-01-01T12:00:00",
"updated_at": "2023-01-01T12:00:00"
}
}