BAE BAE - 10 months ago 50
Python Question

Django: return json only for api sub-app

urlpatterns = patterns(
url(r'^subapp1/', include('subapp1.urls', namespace='subapp1')),
url(r'^api/', include('api.urls')),

GET /api/invalid/url
sent, 404 html page returned. It seems that this is not right for REST APIs.

How to make invalid urls starting with
return 404 html page, and make invalid urls starting with
return 404 status code and error message in json?

Is it possible to set Django to return default response based on
field in the request header? e.g. return 404 html, if
Accept text/html
, return json if
Accept application/json

Any comments welcomed. Thanks.

Answer Source

May the following piece of codes help. From the source codes of django.views.defaults, http.HttpResponseNotFound(body, content_type=content_type) should be returned. so, checking request.path, if starting with /myapp/api, return http.HttpResponseNotFound(body, content_type='application/json'), otherwise, return default response.

from django.views.defaults import page_not_found 

    def customized_page_not_found(request, *args, **kwargs):
        if request.path.startswith('/myapp/api'):
                from django.http import HttpResponseNotFound
                return HttpResponseNotFound( json.dumps( {'error': 'Page Not Found'} ),
            except Exception as e:
                print 'Exception:', e

        return page_not_found( request, *args, **kwargs)

handler404 = customized_page_not_found

Any questions and comments welcomed.