I am following this tutorial here: https://dev.to/nditah/develop-a-simple-python-fastapi-todo-app-in-1-minute-8dg
Most of the requests return a 303 status:
@app.post("/add")
def add(req: Request, title: str = Form(...), db: Session = Depends(get_db)):
new_todo = models.Todo(title=title)
db.add(new_todo)
db.commit()
url = app.url_path_for("home")
return RedirectResponse(url=url, status_code=status.HTTP_303_SEE_OTHER)
@app.get("/update/{todo_id}")
def add(req: Request, todo_id: int, db: Session = Depends(get_db)):
todo = db.query(models.Todo).filter(models.Todo.id == todo_id).first()
todo.complete = not todo.complete
db.commit()
url = app.url_path_for("home")
return RedirectResponse(url=url, status_code=status.HTTP_303_SEE_OTHER)
@app.get("/delete/{todo_id}")
def add(req: Request, todo_id: int, db: Session = Depends(get_db)):
todo = db.query(models.Todo).filter(models.Todo.id == todo_id).first()
db.delete(todo)
db.commit()
url = app.url_path_for("home")
return RedirectResponse(url=url, status_code=status.HTTP_303_SEE_OTHER)
I understand that 303 is a redirect status code, but can anyone explain to me why it would be used in this case? Wouldn't it make more sense to use a status code 200? When I tried to update the status code to:
@app.post("/add")
def add(req: Request, title: str = Form(...), db: Session = Depends(get_db)):
new_todo = models.Todo(title=title)
db.add(new_todo)
db.commit()
url = app.url_path_for("home")
return RedirectResponse(url=url, status_code=status.HTTP_200_OK)
This doesn't work and when I add or update a todo it just takes me to a new empty page. Does anyone have any advice on how I would be able to get status 200 responses instead of 303? The 303 works perfect, but I am not sure I understand the reasoning behind it. Would anyone be able to explain that too?
Locationfield, so when you set a200code, nothing happens since the server isn't telling the browser to redirect the client. The response code is what tells the browser to redirect the user to another resource. The meaning behind303is that it tells the browser semantically that the resource thatLocationpoints to, is a different resource from what was requested.