0

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.

TomásVF
  • 13
  • 6

2 Answers2

0

This should catch all requests under "/api" and give the proper response.

from flask import render_template, jsonify

# assuming you already have your app initiated.

@app.route("/api", defaults={'path': ''})
@app.route("/api/<path:path>")
def api(path):
  try:
    return render_template(path+"/index.html") # try to match the API endpoint
  except: # endpoint not found
    return jsonify({'error': 'endpoint not found'})
vlone
  • 17
  • 5
0

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'
TomásVF
  • 13
  • 6