DEV Community

Discussion on: Develop a Simple Python FastAPI ToDo App in 1 minute

Collapse
 
lil_b_1c4ecb93d28aab19e02 profile image
Lil B • Edited

Hi @nditah this was great! Your app is awesome and I am trying to learn fastapi and python, so this was a great tutorial. I do have a question for you.

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)
Enter fullscreen mode Exit fullscreen mode

I understand that 303 is a redirect status code, but can you 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)
Enter fullscreen mode Exit fullscreen mode

This doesn't work and when I add or update a todo it just takes me to a new empty page. Do you 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 you be able to explain that too?