juggl/backend/src/routes/records.py
linuskmr 426d34a2d3 [WIP] All get, post, update, delete operations with relations working
However, all models are contained in one file for easier debugging. Trying to refactor this back to multiple files
2021-12-25 19:59:51 +01:00

89 lines
2.6 KiB
Python

from fastapi import APIRouter, status, Path, Depends, HTTPException
from sqlmodel import select, Session
from src import database
from src.models.models import Record, RecordRead, RecordCreate
router = APIRouter(prefix="/records", tags=["Records"])
@router.get("/", response_model=list[RecordRead], summary="Get a list of all records")
async def all_records(
*,
session: Session = Depends(database.get_session)
) -> list[Record]:
"""Returns a list of all records."""
records = session.exec(select(Record)).all()
return records
@router.post("/", status_code=status.HTTP_201_CREATED)
async def add_record(
*,
record: RecordCreate,
session: Session = Depends(database.get_session)
):
"""Start a record."""
db_record = Record.from_orm(record)
session.add(db_record)
session.commit()
session.refresh(db_record)
return db_record
@router.get("/{id}", response_model=RecordRead)
async def get_record(
*,
id: str = Path(..., title="ID of the record"),
session: Session = Depends(database.get_session)
) -> Record:
"""Fetch a record by id."""
record = session.get(Record, id)
if not record:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
return record
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_record(
*,
id: str = Path(..., title="ID of the record"),
session: Session = Depends(database.get_session)
):
"""Delete a record specified by id."""
record = session.get(Record, id)
if not record:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
session.delete(record)
session.commit()
# TODO: This method implicitly returns None, which will be converted to null by FastAPI, which triggers a
# warning, because the method returns with header HTTP_204_NO_CONTENT, but has content
@router.patch("/{id}", summary="Apply partial updates to a record by id")
async def patch_record(
*,
record: RecordCreate,
id: str = Path(..., title="ID of the record"),
session: Session = Depends(database.get_session)
):
"""Apply partial updates to a record."""
# Fetch record by id from database
db_record = session.get(Record, id)
if not db_record:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
# Set all provided arguments in the database record
for key, value in record.dict(exclude_unset=True).items():
setattr(db_record, key, value)
# Write modified record to database
session.add(db_record)
session.commit()
session.refresh(db_record)
return db_record