Feat: post and put redirect to get method

This commit is contained in:
2022-12-31 14:55:24 +01:00
parent ccb59975f7
commit a953631d19
3 changed files with 28 additions and 20 deletions

View File

@@ -1,7 +1,7 @@
import sqlite3
from fastapi import FastAPI, status
from fastapi.responses import JSONResponse, Response
from fastapi.responses import JSONResponse, RedirectResponse, Response
from backend.adapters.sqlite import create_db
from backend.api.model import StudentModel, TribeModel
@@ -35,7 +35,7 @@ student_repo = StudentSQLiteRepository(conn)
app = FastAPI()
@app.post("/tribes", status_code=status.HTTP_201_CREATED, response_model=TribeModel)
@app.post("/tribes", response_class=RedirectResponse, status_code=status.HTTP_302_FOUND)
async def post_tribe(item: TribeModel):
try:
tribe = services.add_tribe(
@@ -47,10 +47,12 @@ async def post_tribe(item: TribeModel):
content=f"The tribe {item.name} already exists",
)
return tribe.to_dict()
return f"/tribes/{tribe.name}"
@app.put("/tribes/{name}", status_code=status.HTTP_200_OK, response_model=TribeModel)
@app.put(
"/tribes/{name}", response_class=RedirectResponse, status_code=status.HTTP_302_FOUND
)
async def put_tribe(name: str, item: TribeModel):
try:
tribe = services.update_tribe(
@@ -62,7 +64,7 @@ async def put_tribe(name: str, item: TribeModel):
content=f"The tribe {name} does not exists",
)
return tribe.to_dict()
return f"/tribes/{tribe.name}"
@app.delete("/tribes/{name}")
@@ -94,7 +96,9 @@ async def get_tribe(name: str):
return tribe.to_dict()
@app.post("/students", status_code=status.HTTP_201_CREATED, response_model=StudentModel)
@app.post(
"/students", response_class=RedirectResponse, status_code=status.HTTP_302_FOUND
)
async def post_student(item: StudentModel):
if item.id is not None:
return JSONResponse(
@@ -116,7 +120,7 @@ async def post_student(item: StudentModel):
content=f"The tribe {item.tribe_name} does not exists. You can't add a student in it.",
)
return student.to_dict()
return f"/students/{student.id}"
@app.get("/students/{id}", status_code=status.HTTP_200_OK, response_model=StudentModel)
@@ -136,8 +140,8 @@ async def list_students():
@app.put(
"/students/{student_id}",
status_code=status.HTTP_200_OK,
response_model=StudentModel,
response_class=RedirectResponse,
status_code=status.HTTP_302_FOUND,
)
async def put_student(student_id, item: StudentModel):
if student_id != item.id:
@@ -166,7 +170,7 @@ async def put_student(student_id, item: StudentModel):
content=f"The student {item.name} ({item.id=}) does not exists. You can't modify it.",
)
return student.to_dict()
return f"/students/{student.id}"
@app.delete(