python-webservice/controllers/album.py

64 lines
2.0 KiB
Python
Raw Normal View History

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:16:52 +00:00
import models
2022-10-14 18:34:11 +00:00
import models.schemas
import models.album
2022-10-14 18:03:52 +00:00
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
2022-10-14 18:34:11 +00:00
@router.get("/albums", response_model=models.schemas.Albums)
def list_albums(self):
2022-10-14 17:52:31 +00:00
2022-10-14 18:34:11 +00:00
albums_list = models.album.get_all_albums(self.session)
response = {"data": albums_list}
2022-10-14 17:52:31 +00:00
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")
2022-10-14 18:16:52 +00:00
def add_album(self, album: models.schemas.AlbumBase):
2022-10-14 17:52:31 +00:00
try:
2022-10-14 18:16:52 +00:00
album = models.album.create_album(self.session, album)
2022-10-14 17:52:31 +00:00
return album
2022-10-14 18:16:52 +00:00
except models.exceptions.AlbumException as ex:
2022-10-14 17:52:31 +00:00
raise HTTPException(**ex.__dict__)
# API endpoint to get info of a particular album
2022-10-14 18:16:52 +00:00
@router.get("/albums/{album_id}", response_model=models.schemas.Album)
2022-10-14 17:52:31 +00:00
def get_album(album_id: int, session: Session = Depends(get_db)):
try:
2022-10-14 18:16:52 +00:00
album = models.album.get_album_by_id(session, album_id)
2022-10-14 17:52:31 +00:00
return album
2022-10-14 18:16:52 +00:00
except models.exceptions.AlbumException as ex:
2022-10-14 17:52:31 +00:00
raise HTTPException(**ex.__dict__)
2022-10-14 18:39:57 +00:00
# API to update an existing album info
2022-10-14 18:16:52 +00:00
@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)):
2022-10-14 17:52:31 +00:00
try:
2022-10-14 18:16:52 +00:00
album = models.album.update_album(session, album_id, new_info)
2022-10-14 17:52:31 +00:00
return album
2022-10-14 18:16:52 +00:00
except models.exceptions.AlbumException as ex:
2022-10-14 17:52:31 +00:00
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:
2022-10-14 18:16:52 +00:00
return models.album.delete_album(session, album_id)
except models.exceptions.AlbumException as ex:
2022-10-14 17:52:31 +00:00
raise HTTPException(**ex.__dict__)