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?

coolbeanz
  • 3
  • 2
  • Please have a look at some related answers [here](https://stackoverflow.com/a/70777217/17865804) and [here](https://stackoverflow.com/a/73088816/17865804). – Chris Sep 08 '22 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. – MatsLindh Sep 08 '22 at 19:12

0 Answers0