0

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?

2
  • Please have a look at some related answers here and here. Commented Sep 8, 2022 at 17:08
  • Only redirect responses (3xx) causes the browser to follow the Location field, so when you set a 200 code, 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 behind 303 is that it tells the browser semantically that the resource that Location points to, is a different resource from what was requested. Commented Sep 8, 2022 at 19:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.