Solution details

In Django, you can create a basic service without any third-party packages. Instead of returning HTML, you can return the serialized data in the JSON format.

For example, we can create a simple service that returns five recent public posts from SuperBook as follows:

from django.http import JsonResponse class PublicPostJSONView(View): 
 
    def get(self, request, *args, **kwargs): 
        msgs = models.Post.objects.public_posts().values( 
            "posted_by_id", "message")[:5] 
        return JsonResponse(list(msgs), safe=False) 

If we try to retrieve this view, we will get a JSON string rather than an HTML response:

    >>> from django.test import Client
    >>> Client().get("http://0.0.0.0:8000/public/").content
    b'[{"posted_by_id": 23, "message": "Hello!"},

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.