from fastapi import APIRouter, Depends, HTTPException from fastapi_utils.cbv import cbv from sqlalchemy.orm import Session from crud import get_all_albums, create_album, get_album_by_id, update_album, delete_album from database import get_db from exceptions import AlbumException from schemas import Album, CreateAndUpdateAlbum, PaginatedAlbum 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 # API endpoint to add a album info to the database @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__) # API to delete a album info from the data base @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__)