feat: add endpoint and database model for creating books ✅ (auto-linted)
This commit is contained in:
parent
a406e295e1
commit
ea44a8bbf6
30
alembic/versions/20250429_115732_97a829da_update_book.py
Normal file
30
alembic/versions/20250429_115732_97a829da_update_book.py
Normal file
@ -0,0 +1,30 @@
|
||||
"""create table for books
|
||||
Revision ID: 1d6a9f58e2f1
|
||||
Revises: 0001
|
||||
Create Date: 2023-05-11 15:18:36.631658
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '1d6a9f58e2f1'
|
||||
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('description', sa.String(), nullable=True),
|
||||
sa.Column('year_published', sa.Integer(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),
|
||||
sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now(), onupdate=sa.func.now()),
|
||||
sa.Column('author_id', sa.String(36), sa.ForeignKey('authors.id'), nullable=False)
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table('books')
|
@ -0,0 +1,23 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, 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, get_all_books
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/books", status_code=status.HTTP_201_CREATED, response_model=BookSchema)
|
||||
async def create_new_book(
|
||||
book: BookCreate,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
new_book = create_book(db=db, book_data=book)
|
||||
return new_book
|
||||
|
||||
@router.get("/books", status_code=200, response_model=List[BookSchema])
|
||||
async def get_books(
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
books = get_all_books(db)
|
||||
return books
|
61
helpers/book_helpers.py
Normal file
61
helpers/book_helpers.py
Normal file
@ -0,0 +1,61 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from models.book import Book
|
||||
from models.author import Author
|
||||
from schemas.book import BookCreate, BookSchema
|
||||
|
||||
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.
|
||||
"""
|
||||
authors = [db.query(Author).get(author_id) for author_id in book_data.author_ids]
|
||||
if any(author is None for author in authors):
|
||||
raise ValueError("One or more author IDs are invalid")
|
||||
|
||||
db_book = Book(
|
||||
title=book_data.title,
|
||||
description=book_data.description,
|
||||
year_published=book_data.year_published,
|
||||
authors=authors
|
||||
)
|
||||
db.add(db_book)
|
||||
db.commit()
|
||||
db.refresh(db_book)
|
||||
return db_book
|
||||
|
||||
def get_book_by_id(db: Session, book_id: uuid.UUID) -> Optional[BookSchema]:
|
||||
"""
|
||||
Retrieves a single book by its ID.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
book_id (UUID): The ID of the book to retrieve.
|
||||
|
||||
Returns:
|
||||
Optional[BookSchema]: The book schema object if found, otherwise None.
|
||||
"""
|
||||
book = db.query(Book).filter(Book.id == book_id).first()
|
||||
if book:
|
||||
return BookSchema.from_orm(book)
|
||||
return None
|
||||
|
||||
def get_all_books(db: Session) -> List[BookSchema]:
|
||||
"""
|
||||
Retrieves all books from the database.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
|
||||
Returns:
|
||||
List[BookSchema]: A list of all book schema objects.
|
||||
"""
|
||||
books = db.query(Book).all()
|
||||
return [BookSchema.from_orm(book) for book in books]
|
26
models/book.py
Normal file
26
models/book.py
Normal file
@ -0,0 +1,26 @@
|
||||
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from core.database import Base
|
||||
import uuid
|
||||
|
||||
class Author(Base):
|
||||
__tablename__ = "authors"
|
||||
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
name = Column(String, nullable=False)
|
||||
books = relationship("Book", back_populates="authors")
|
||||
|
||||
class Book(Base):
|
||||
__tablename__ = "books"
|
||||
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
title = Column(String, nullable=False)
|
||||
description = Column(String, nullable=True)
|
||||
year_published = Column(Integer, nullable=False)
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
||||
|
||||
author_id = Column(UUID, ForeignKey("authors.id"), nullable=False)
|
||||
authors = relationship("Author", back_populates="books")
|
@ -7,3 +7,6 @@ sqlalchemy>=1.4.0
|
||||
python-dotenv>=0.19.0
|
||||
bcrypt>=3.2.0
|
||||
alembic>=1.13.1
|
||||
jose
|
||||
passlib
|
||||
pydantic
|
||||
|
27
schemas/book.py
Normal file
27
schemas/book.py
Normal file
@ -0,0 +1,27 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, List
|
||||
from datetime import datetime
|
||||
import uuid
|
||||
|
||||
class BookBase(BaseModel):
|
||||
title: str = Field(..., description="Book title")
|
||||
description: Optional[str] = Field(None, description="Book description")
|
||||
year_published: int = Field(..., description="Year the book was published")
|
||||
|
||||
class BookCreate(BookBase):
|
||||
author_ids: List[uuid.UUID] = Field(..., description="List of author IDs")
|
||||
|
||||
class BookUpdate(BookBase):
|
||||
title: Optional[str] = Field(None, description="Book title")
|
||||
description: Optional[str] = Field(None, description="Book description")
|
||||
year_published: Optional[int] = Field(None, description="Year the book was published")
|
||||
author_ids: Optional[List[uuid.UUID]] = Field(None, description="List of author IDs")
|
||||
|
||||
class BookSchema(BookBase):
|
||||
id: uuid.UUID
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
author_ids: List[uuid.UUID] = Field(..., description="List of author IDs")
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
Loading…
x
Reference in New Issue
Block a user