|
| 1 | +from typing import List |
| 2 | + |
| 3 | +from app.api import crud |
| 4 | +from app.api.models import NoteDB, NoteSchema |
| 5 | +from fastapi import APIRouter, HTTPException, Path |
| 6 | + |
| 7 | +router = APIRouter() |
| 8 | + |
| 9 | + |
| 10 | +@router.post("/", response_model=NoteDB, status_code=201) |
| 11 | +async def create_note(payload: NoteSchema): |
| 12 | + note_id = await crud.post(payload) |
| 13 | + |
| 14 | + response_object = { |
| 15 | + "id": note_id, |
| 16 | + "title": payload.title, |
| 17 | + "description": payload.description, |
| 18 | + } |
| 19 | + return response_object |
| 20 | + |
| 21 | + |
| 22 | +@router.get("/{id}/", response_model=NoteDB) |
| 23 | +async def read_note(id: int = Path(..., gt=0),): |
| 24 | + note = await crud.get(id) |
| 25 | + if not note: |
| 26 | + raise HTTPException(status_code=404, detail="Note not found") |
| 27 | + return note |
| 28 | + |
| 29 | + |
| 30 | +@router.get("/", response_model=List[NoteDB]) |
| 31 | +async def read_all_notes(): |
| 32 | + return await crud.get_all() |
| 33 | + |
| 34 | + |
| 35 | +@router.put("/{id}/", response_model=NoteDB) |
| 36 | +async def update_note(payload: NoteSchema, id: int = Path(..., gt=0),): |
| 37 | + note = await crud.get(id) |
| 38 | + if not note: |
| 39 | + raise HTTPException(status_code=404, detail="Note not found") |
| 40 | + |
| 41 | + note_id = await crud.put(id, payload) |
| 42 | + |
| 43 | + response_object = { |
| 44 | + "id": note_id, |
| 45 | + "title": payload.title, |
| 46 | + "description": payload.description, |
| 47 | + } |
| 48 | + return response_object |
| 49 | + |
| 50 | + |
| 51 | +@router.delete("/{id}/", response_model=NoteDB) |
| 52 | +async def delete_note(id: int = Path(..., gt=0)): |
| 53 | + note = await crud.get(id) |
| 54 | + if not note: |
| 55 | + raise HTTPException(status_code=404, detail="Note not found") |
| 56 | + |
| 57 | + await crud.delete(id) |
| 58 | + |
| 59 | + return note |
0 commit comments