feat: add book creation endpoint with database persistence
This commit is contained in:
parent
bb577cbdb6
commit
3741788b29
32
alembic/versions/20250429_182027_3c1332db_update_book.py
Normal file
32
alembic/versions/20250429_182027_3c1332db_update_book.py
Normal file
@ -0,0 +1,32 @@
|
||||
"""Initial creation of Book model
|
||||
Revision ID: a1b2c3d4e5f6
|
||||
Revises: 0001
|
||||
Create Date: 2023-11-17 10:00:00.000000
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '3c1332db'
|
||||
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('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')
|
@ -0,0 +1,23 @@
|
||||
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
|
||||
|
||||
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
|
||||
"""
|
||||
new_book = create_book(db=db, book_data=book_data)
|
||||
if not new_book:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Could not create book"
|
||||
)
|
||||
return new_book
|
80
helpers/book_helpers.py
Normal file
80
helpers/book_helpers.py
Normal file
@ -0,0 +1,80 @@
|
||||
from typing import Optional, List
|
||||
from sqlalchemy.orm import Session
|
||||
from uuid import UUID
|
||||
|
||||
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 get_book_by_id(db: Session, book_id: UUID) -> Optional[Book]:
|
||||
"""
|
||||
Retrieves a book by its ID.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
book_id (UUID): The ID of the book to retrieve.
|
||||
|
||||
Returns:
|
||||
Optional[Book]: The book object if found, otherwise None.
|
||||
"""
|
||||
return db.query(Book).filter(Book.id == book_id).first()
|
||||
|
||||
def get_books_by_author(db: Session, author: str, skip: int = 0, limit: int = 100) -> List[Book]:
|
||||
"""
|
||||
Retrieves books by a specific author.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
author (str): The author name to filter by.
|
||||
skip (int, optional): Number of records to skip for pagination. Defaults to 0.
|
||||
limit (int, optional): Maximum number of records to return. Defaults to 100.
|
||||
|
||||
Returns:
|
||||
List[Book]: A list of books by the specified author.
|
||||
"""
|
||||
return db.query(Book).filter(Book.author == author).offset(skip).limit(limit).all()
|
||||
|
||||
def get_books_by_title(db: Session, title: str, skip: int = 0, limit: int = 100) -> List[Book]:
|
||||
"""
|
||||
Retrieves books by a specific title or partial title match.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
title (str): The title or partial title to search for.
|
||||
skip (int, optional): Number of records to skip for pagination. Defaults to 0.
|
||||
limit (int, optional): Maximum number of records to return. Defaults to 100.
|
||||
|
||||
Returns:
|
||||
List[Book]: A list of books matching the title search.
|
||||
"""
|
||||
return db.query(Book).filter(Book.title.ilike(f"%{title}%")).offset(skip).limit(limit).all()
|
||||
|
||||
def get_all_books(db: Session, skip: int = 0, limit: int = 100) -> List[Book]:
|
||||
"""
|
||||
Retrieves all books with pagination.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
skip (int, optional): Number of records to skip for pagination. Defaults to 0.
|
||||
limit (int, optional): Maximum number of records to return. Defaults to 100.
|
||||
|
||||
Returns:
|
||||
List[Book]: A list of book objects.
|
||||
"""
|
||||
return db.query(Book).offset(skip).limit(limit).all()
|
19
models/book.py
Normal file
19
models/book.py
Normal file
@ -0,0 +1,19 @@
|
||||
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 Book(Base):
|
||||
__tablename__ = "books"
|
||||
|
||||
# Primary key using UUID
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
|
||||
# Book details
|
||||
title = Column(String, nullable=False, index=True)
|
||||
author = Column(String, nullable=False, index=True)
|
||||
|
||||
# Timestamps
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
@ -7,3 +7,6 @@ sqlalchemy>=1.4.0
|
||||
python-dotenv>=0.19.0
|
||||
bcrypt>=3.2.0
|
||||
alembic>=1.13.1
|
||||
jose
|
||||
passlib
|
||||
pydantic
|
||||
|
36
schemas/book.py
Normal file
36
schemas/book.py
Normal file
@ -0,0 +1,36 @@
|
||||
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")
|
||||
|
||||
# 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")
|
||||
|
||||
# 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",
|
||||
"created_at": "2023-01-01T12:00:00",
|
||||
"updated_at": "2023-01-01T12:00:00"
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user