Search code examples
pythondjangodjango-rest-frameworkexceptionhandler

How can I return a custom response for non-existent endpoints?


how can I return JSON response for queries to non-existent endpoints?

For example: query to /api/rock?q=123, but the api have /api/paper only, and then the server return {'error': 'endpoint not found'} or something.

I'm using Django Rest Framework 3.14.0, Django 4.1.7, help please.

I checked exception_handler in views.py, but how can I return a custom response for non-existent endpoints?

I've read the documentation, but I can't get this done. Returns the default response for Django resources not found.


Solution

  • I solved it, my intention was, having given endpoints, eg: /api/paper, when the api receives requests for other non-existent endpoints, the server will return a json response like {"error": "endpoint does not exist".}.

    How I solved it:

    In the root of the project, in urls.py of the root, added handler404 = 'utils.views.error_404'

    • Project structure:
    |- root
    |   |- urls.py
    |
    |- utils
    |  |- views.py
    |
    |- app
    
    • views.py
    from django.http import JsonResponse
    
    def error_404(request, exception):
        message = "Resource not found."
        return JsonResponse(data={'message': message}, status=404)
    
    
    def error_500(exception):
        message = "D\'oh, something was wrong."
        return JsonResponse(data={'error': message}, status=404)
    
    • urls.py
    handler404 = 'utils.views.error_404'
    handler500 = 'utils.views.error_500'