Can anybody help me to understand why not raise an HTTPException
when the status is 200 instead a return
?
working with fastApi
A code as example:
@app.delete("/delete")
def delete(id = Query(...,description="Delete ID to be deleted")):
if id not in dictionary:
raise HTTPException(status_code=404,detail="Delete Id doesn't exists.")
del dictionary[id]
return {"Success":"Delete deleted!"}
I want to understand why not to use as example:
raise HTTPException(status_code=200,detail="Delete deleted!")
Is this a correct way to use it?
First of all because of the semantics: an exception is a language construct that means something else than returning the result of a function. It breaks the normal flow of the FastAPI application, and I'm guessing it will/could break most middleware handling (such as CORS headers) because suddenly an exception has occurred instead.
Secondly: Because you probably want to return something else than just information under a detail
key. It won't be able to use the response_model
mechanism that's built-in to FastAPI and allows you to tweak and validate the response model for each type of request declaratively (i.e. by configuring the view decorator).