DEV Community

Lee Packham
Lee Packham

Posted on

Converting a request HTTPError to Django Rest Framework

Today I was working on a piece of code sits in a Django Rest Framework view and had an issue where I needed to call an external Rest API and still return the actual error rather than an "Internal Service Error".

Essentially the original code deep within a library went:

result = requests.get(url)
result.raise_for_status()
Enter fullscreen mode Exit fullscreen mode

So when calling this from a view, any error would directly translate to an internal server error. DRF includes APIException which is expected to be sub-classed so I did that with a a small init to take a status code instead of relying on the sub-class defining it.

class GenericAPIException(APIException):
    def __init__(self, status_code):
        self.status_code = status_code
        super(GenericAPIException, self).__init__()
Enter fullscreen mode Exit fullscreen mode

This meant that in my View:

try:
    r = do_the_api_call()
except HTTPError as e:
    raise GenericAPIException(e.response.status_code)
Enter fullscreen mode Exit fullscreen mode

This then meant that the status code proxies out via the view.

Top comments (0)