Skip to content
This repository has been archived by the owner on Sep 17, 2023. It is now read-only.

17 Rolling your own API

scotwk edited this page May 10, 2015 · 2 revisions

Django can return more than just HTML pages, it can be configured to return JSON (or other data formats).

JSON view

Make a view that returns JSON.

from django.views.generic.list import BaseListView
from django.http import JsonResponse

class JSONListView(LoginRequiredMixin, BaseListView):
    model = Note

    def get_queryset(self):
        return Note.objects.filter(owner=self.request.user).order_by('-pub_date'),

    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()

        notes = []
        for note in self.object_list[0]:
            notes.append({
                'title': note.title,
                'body': note.body,
                'pub_date': note.pub_date,
            })

        response = {
            'user': self.request.user.username,
            'notes': notes,
            'count': len(notes),
        }
        
        return JsonResponse(response, **kwargs)

URLs

Don't forget a URL for your new view:

url(r'^api/v1/list/$', JSONListView.as_view(), name='json-list')

Test

Don't forget to test your new JSON endpoint.