1

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?

Ragnar
  • 171
  • 3
  • 13
  • 4
    Because a successful operation is (hopefully) not very exceptional. Same reason you don't get a ticket for having _not_ speeded through an intersection at green light. – Amadan May 01 '22 at 19:17
  • 1
    Exceptions are expensive, since they need to collect the traceback. They also bypass normal return flow which makes functions work differently then expected. In general you only want to use them in very rare situations, like if something is wrong. – mousetail May 01 '22 at 19:25
  • 1
    Exceptions in Python are rather lightweight and Python uses them a bit more for flow control than what other languages do (ask for forgiveness, not permission). They're still wrong for this use case, however. – MatsLindh May 02 '22 at 06:57

2 Answers2

3

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).

MatsLindh
  • 49,529
  • 4
  • 53
  • 84
0
  1. return is better
  2. A lot of times the result should be equal
  3. raise breaks all next middlewares (pre, mid, post)
  4. Here is redirect login page middleware
class Middleware(APIRoute):
    def get_route_handler(self) -> Callable:
        original_route_handler = super().get_route_handler()

    async def custom_route_handler(req: Request) -> Response:
        try:
            res: Response = await original_route_handler(req) #original request
        except HTTPException as e: #catch login exception
            if e.status_code == status.HTTP_403_FORBIDDEN:
                return RedirectResponse(url = Const.DEFAULT_PAGE) #redirect to home page
            else:
                raise e #other exception process normally 
            
        return res

    return custom_route_handler
  • The way to implement the middleware is correct however I do not believe to say `return` is better than an `HTTP Exception` I don't think is the correct reason to say I should use one or another. The reason is such more simple as HTTP Exception indicates an error while HTTP status code 200 is not an error. So return is a better approach to a success message and HTTP Exception for an error. – Ragnar Mar 25 '23 at 02:50