feat: add POST endpoint to create books by title and author

This commit is contained in:
Backend IM Bot 2025-04-29 19:09:30 +00:00
parent c042992398
commit 233c84fd09
6 changed files with 172 additions and 0 deletions

View File

@ -0,0 +1,34 @@
"""Initial creation of books table
Revision ID: 1a2b3c4d5e6f
Revises: 0001
Create Date: 2023-07-21 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(
'books',
sa.Column('id', sa.String(36), primary_key=True),
sa.Column('title', sa.String(), nullable=False),
sa.Column('author', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
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_books_title'), 'books', ['title'], unique=False)
op.create_index(op.f('ix_books_author'), 'books', ['author'], unique=False)
def downgrade():
op.drop_index(op.f('ix_books_author'), table_name='books')
op.drop_index(op.f('ix_books_title'), table_name='books')
op.drop_table('books')

View File

@ -0,0 +1,26 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from core.database import get_db
from schemas.book import BookCreate, BookSchema
from helpers.book_helpers import create_book, book_exists
router = APIRouter()
@router.post("/books", status_code=status.HTTP_201_CREATED, response_model=BookSchema)
async def add_book(
book_data: BookCreate,
db: Session = Depends(get_db)
):
"""
Add a new book to the database using title and author
"""
# Check if book already exists
if book_exists(db, book_data.title, book_data.author):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Book with this title and author already exists"
)
# Create the book
new_book = create_book(db, book_data)
return new_book

50
helpers/book_helpers.py Normal file
View File

@ -0,0 +1,50 @@
from typing import Optional
from sqlalchemy.orm import Session
from models.book import Book
from schemas.book import BookCreate
def create_book(db: Session, book_data: BookCreate) -> Book:
"""
Creates a new book in the database.
Args:
db (Session): The database session.
book_data (BookCreate): The data for the book to create.
Returns:
Book: The newly created book object.
"""
db_book = Book(**book_data.dict())
db.add(db_book)
db.commit()
db.refresh(db_book)
return db_book
def find_book_by_title_and_author(db: Session, title: str, author: str) -> Optional[Book]:
"""
Finds a book by its title and author.
Args:
db (Session): The database session.
title (str): The title of the book.
author (str): The author of the book.
Returns:
Optional[Book]: The book if found, otherwise None.
"""
return db.query(Book).filter(Book.title == title, Book.author == author).first()
def book_exists(db: Session, title: str, author: str) -> bool:
"""
Checks if a book with the given title and author already exists.
Args:
db (Session): The database session.
title (str): The title of the book.
author (str): The author of the book.
Returns:
bool: True if the book exists, False otherwise.
"""
book = find_book_by_title_and_author(db, title, author)
return book is not None

20
models/book.py Normal file
View File

@ -0,0 +1,20 @@
from sqlalchemy import Column, String, DateTime, Text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from core.database import Base
import uuid
class Book(Base):
__tablename__ = "books"
# Primary key using UUID
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
# Basic fields
title = Column(String, nullable=False, index=True)
author = Column(String, nullable=False, index=True)
description = Column(Text, nullable=True)
# Timestamps
created_at = Column(DateTime, default=func.now())
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

View File

@ -7,3 +7,6 @@ sqlalchemy>=1.4.0
python-dotenv>=0.19.0 python-dotenv>=0.19.0
bcrypt>=3.2.0 bcrypt>=3.2.0
alembic>=1.13.1 alembic>=1.13.1
jose
passlib
pydantic

39
schemas/book.py Normal file
View File

@ -0,0 +1,39 @@
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
from uuid import UUID
# Base schema for Book, used for inheritance
class BookBase(BaseModel):
title: str = Field(..., description="Book title")
author: str = Field(..., description="Book author")
description: Optional[str] = Field(None, description="Book description")
# Schema for creating a new Book
class BookCreate(BookBase):
pass
# Schema for updating an existing Book (all fields optional)
class BookUpdate(BaseModel):
title: Optional[str] = Field(None, description="Book title")
author: Optional[str] = Field(None, description="Book author")
description: Optional[str] = Field(None, description="Book description")
# Schema for representing a Book in responses
class BookSchema(BookBase):
id: UUID
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True
schema_extra = {
"example": {
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"description": "A novel about the American Dream",
"created_at": "2023-01-01T12:00:00",
"updated_at": "2023-01-01T12:00:00"
}
}