2022-10-14 17:52:31 +00:00
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
|
|
from fastapi_utils.cbv import cbv
|
|
|
|
from sqlalchemy.orm import Session
|
2022-10-14 18:03:52 +00:00
|
|
|
|
2022-10-14 18:01:04 +00:00
|
|
|
from models.album import get_all_albums, create_album, get_album_by_id, update_album, delete_album, AlbumException
|
2022-10-14 18:03:52 +00:00
|
|
|
from models.schemas import Album, CreateAndUpdateAlbum, PaginatedAlbum
|
|
|
|
|
2022-10-14 17:52:31 +00:00
|
|
|
from database import get_db
|
|
|
|
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
|
|
|
|
|
|
@cbv(router)
|
|
|
|
class Albums:
|
|
|
|
session: Session = Depends(get_db)
|
|
|
|
|
|
|
|
# API to get the list of album info
|
|
|
|
@router.get("/albums", response_model=PaginatedAlbum)
|
|
|
|
def list_albums(self, limit: int = 10, offset: int = 0):
|
|
|
|
|
|
|
|
albums_list = get_all_albums(self.session, limit, offset)
|
|
|
|
response = {"limit": limit, "offset": offset, "data": albums_list}
|
|
|
|
|
|
|
|
return response
|
|
|
|
|
2022-10-14 18:01:04 +00:00
|
|
|
# API endpoint to add an album to the database
|
2022-10-14 17:52:31 +00:00
|
|
|
@router.post("/albums")
|
|
|
|
def add_album(self, album: CreateAndUpdateAlbum):
|
|
|
|
|
|
|
|
try:
|
|
|
|
album = create_album(self.session, album)
|
|
|
|
return album
|
|
|
|
except AlbumException as ex:
|
|
|
|
raise HTTPException(**ex.__dict__)
|
|
|
|
|
|
|
|
|
|
|
|
# API endpoint to get info of a particular album
|
|
|
|
@router.get("/albums/{album_id}", response_model=Album)
|
|
|
|
def get_album(album_id: int, session: Session = Depends(get_db)):
|
|
|
|
try:
|
|
|
|
album = get_album_by_id(session, album_id)
|
|
|
|
return album
|
|
|
|
except AlbumException as ex:
|
|
|
|
raise HTTPException(**ex.__dict__)
|
|
|
|
|
|
|
|
|
|
|
|
# API to update a existing album info
|
|
|
|
@router.put("/albums/{album_id}", response_model=Album)
|
|
|
|
def update_album(album_id: int, new_info: CreateAndUpdateAlbum, session: Session = Depends(get_db)):
|
|
|
|
try:
|
|
|
|
album = update_album(session, album_id, new_info)
|
|
|
|
return album
|
|
|
|
except AlbumException as ex:
|
|
|
|
raise HTTPException(**ex.__dict__)
|
|
|
|
|
|
|
|
|
2022-10-14 18:01:04 +00:00
|
|
|
# API to delete an album info from the database
|
2022-10-14 17:52:31 +00:00
|
|
|
@router.delete("/albums/{album_id}")
|
|
|
|
def delete_album(album_id: int, session: Session = Depends(get_db)):
|
|
|
|
try:
|
|
|
|
return delete_album(session, album_id)
|
|
|
|
except AlbumException as ex:
|
|
|
|
raise HTTPException(**ex.__dict__)
|