from fastapi import APIRouter, Depends, HTTPException from fastapi_utils.cbv import cbv from sqlalchemy.orm import Session import models 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=models.schemas.PaginatedAlbum) def list_albums(self, limit: int = 10, offset: int = 0): albums_list = models.album.get_all_albums(self.session, limit, offset) response = {"limit": limit, "offset": offset, "data": albums_list} return response # API endpoint to add an album to the database @router.post("/albums") def add_album(self, album: models.schemas.AlbumBase): try: album = models.album.create_album(self.session, album) return album except models.exceptions.AlbumException as ex: raise HTTPException(**ex.__dict__) # API endpoint to get info of a particular album @router.get("/albums/{album_id}", response_model=models.schemas.Album) def get_album(album_id: int, session: Session = Depends(get_db)): try: album = models.album.get_album_by_id(session, album_id) return album except models.exceptions.AlbumException as ex: raise HTTPException(**ex.__dict__) # API to update a existing album info @router.put("/albums/{album_id}", response_model=models.schemas.Album) def update_album(album_id: int, new_info: models.schemas.AlbumBase, session: Session = Depends(get_db)): try: album = models.album.update_album(session, album_id, new_info) return album except models.exceptions.AlbumException as ex: raise HTTPException(**ex.__dict__) # API to delete an album info from the database @router.delete("/albums/{album_id}") def delete_album(album_id: int, session: Session = Depends(get_db)): try: return models.album.delete_album(session, album_id) except models.exceptions.AlbumException as ex: raise HTTPException(**ex.__dict__)