When a user inputs a url that is wrong, my Django app returns an HTML error. How can I get DRF to return a json formatted error?
Currently my urls is
from django.conf.urls import url
from snippets import views
urlpatterns = [
url(r'^snippets/$', views.snippet_list),
url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
]
but if a user goes to 127.0.0.1:8000/snip They get the html formatted error rather than a json formatted error.
Simply way to do it, you can use
raise Http404
, here is yourviews.py
You also can handle it with
Response(status=status.HTTP_404_NOT_FOUND)
, this answer is how to do with it: https://stackoverflow.com/a/24420524/6396981But previously, inside your
serializer.py
To test it, an example using
curl
command;Hope it can help..
Update
If you want to handle for all error 404 urls with DRF, DRF also provide about it with
APIException
, this answer may help you; https://stackoverflow.com/a/30628065/6396981I'll give an example how do with it;
1.
views.py
2.
urls.py