-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add books model and post endpoint to create new books
- Loading branch information
1 parent
6458f83
commit 233a2e8
Showing
8 changed files
with
212 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
from http import HTTPStatus | ||
from typing import Annotated | ||
|
||
from fastapi import APIRouter, Depends, HTTPException | ||
from sqlalchemy import select | ||
from sqlalchemy.exc import IntegrityError | ||
from sqlalchemy.orm import Session | ||
|
||
from madr.database import get_session | ||
from madr.models import Book, Novelist, User | ||
from madr.schemas import BookPublic, BookSchema | ||
from madr.security import get_current_user | ||
from madr.utils import sanitize | ||
|
||
router = APIRouter(prefix='/books', tags=['books']) | ||
|
||
T_CurrentUser = Annotated[User, Depends(get_current_user)] | ||
T_Session = Annotated[Session, Depends(get_session)] | ||
|
||
|
||
@router.post('/', status_code=HTTPStatus.CREATED, response_model=BookPublic) | ||
def create_book(book: BookSchema, session: T_Session, user: T_CurrentUser): | ||
novelist = session.scalar( | ||
select(Novelist).where(Novelist.id == book.novelist_id) | ||
) | ||
|
||
if not novelist: | ||
raise HTTPException( | ||
status_code=HTTPStatus.NOT_FOUND, | ||
detail='Novelist ID not found', | ||
) | ||
|
||
new_book = Book(year=book.year, title=sanitize(book.title)) | ||
new_book.novelist = novelist | ||
|
||
try: | ||
session.add(new_book) | ||
session.commit() | ||
session.refresh(new_book) | ||
except IntegrityError: | ||
session.rollback() | ||
raise HTTPException( | ||
status_code=HTTPStatus.CONFLICT, | ||
detail='Book already exists in MADR', | ||
) | ||
|
||
return new_book |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 40 additions & 0 deletions
40
migrations/versions/cba12017681b_create_books_table_and_relationship_.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
"""create books table and relationship with novelists | ||
Revision ID: cba12017681b | ||
Revises: 5bd57142ab29 | ||
Create Date: 2024-09-01 13:30:20.688056 | ||
""" | ||
from typing import Sequence, Union | ||
|
||
from alembic import op | ||
import sqlalchemy as sa | ||
|
||
|
||
# revision identifiers, used by Alembic. | ||
revision: str = 'cba12017681b' | ||
down_revision: Union[str, None] = '5bd57142ab29' | ||
branch_labels: Union[str, Sequence[str], None] = None | ||
depends_on: Union[str, Sequence[str], None] = None | ||
|
||
|
||
def upgrade() -> None: | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.create_table('books', | ||
sa.Column('id', sa.Integer(), nullable=False), | ||
sa.Column('year', sa.Integer(), nullable=False), | ||
sa.Column('title', sa.String(), nullable=False), | ||
sa.Column('novelist_id', sa.Integer(), nullable=False), | ||
sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), | ||
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), | ||
sa.ForeignKeyConstraint(['novelist_id'], ['novelists.id'], ), | ||
sa.PrimaryKeyConstraint('id'), | ||
sa.UniqueConstraint('title') | ||
) | ||
# ### end Alembic commands ### | ||
|
||
|
||
def downgrade() -> None: | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.drop_table('books') | ||
# ### end Alembic commands ### |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
from http import HTTPStatus | ||
|
||
|
||
def test_create_book(client, novelist, token): | ||
response = client.post( | ||
'/books/', | ||
headers={'Authorization': f'Bearer {token}'}, | ||
json={ | ||
'year': 2024, | ||
'title': 'New Book', | ||
'novelist_id': novelist.id, | ||
}, | ||
) | ||
|
||
assert response.status_code == HTTPStatus.CREATED | ||
assert response.json() == { | ||
'id': 1, | ||
'year': 2024, | ||
'novelist_id': novelist.id, | ||
'title': 'new book', | ||
} | ||
|
||
|
||
def test_create_book_with_unexistent_novelist(client, token): | ||
response = client.post( | ||
'/books/', | ||
headers={'Authorization': f'Bearer {token}'}, | ||
json={ | ||
'year': 2024, | ||
'title': 'the best book of all time ever', | ||
'novelist_id': 1, | ||
}, | ||
) | ||
|
||
assert response.status_code == HTTPStatus.NOT_FOUND | ||
assert response.json() == {'detail': 'Novelist ID not found'} | ||
|
||
|
||
def test_create_book_already_existent(client, token, novelist, book): | ||
response = client.post( | ||
'/books/', | ||
headers={'Authorization': f'Bearer {token}'}, | ||
json={ | ||
'year': 2024, | ||
'title': book.title, | ||
'novelist_id': novelist.id, | ||
}, | ||
) | ||
|
||
assert response.status_code == HTTPStatus.CONFLICT | ||
assert response.json() == {'detail': 'Book already exists in MADR'} | ||
|
||
|
||
def test_create_book_with_unexistent_novelist_id(client, token): | ||
response = client.post( | ||
'/books/', | ||
headers={'Authorization': f'Bearer {token}'}, | ||
json={ | ||
'year': 2024, | ||
'title': 'Book', | ||
'novelist_id': 1, | ||
}, | ||
) | ||
|
||
assert response.status_code == HTTPStatus.NOT_FOUND | ||
assert response.json() == {'detail': 'Novelist ID not found'} |