May 2018
Beginner to intermediate
282 pages
7h 58m
English
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!"},Read now
Unlock full access