[Fixed]-How to build a json REST API in django (without Django REST framework)

18👍

After more googling, I found what I was looking for in the Django docs:
JsonResponse

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

I think googling using the word “REST” was kind of a red herring which made the search space always direct my queries towards “Django REST framework” which is not what I wanted, though I do want to add a RESTful API.

6👍

You can write GET API using this method, but for POST method this will not work.
For Post method we need to use some REST Library.

POST Method will check for CSRF token in the cookies and where it fails to execute the request, as your django server will treat this request as forged.

0👍

You should go with Django Rest Framework but if you want to do it yourself then:

  1. For POST request, if the client is sending you data as JSON, then you can use the json module to read the data from the request body.
import json

def add_new_user(self, request):
    data = request.body.decode('utf8')
    data = json.loads(data)
  1. If plain name/value pair is sent, then use request.POST or request.GET

  2. Use JsonResponse to send the response

  3. After authentication, the server usually send a token to the client. The client then sends that token when sending a request to ‘protected’ api end-point. A custom header (like auth_token) is used to send the token.

In the server code, you need to do something like
request.META[‘HTTP_AUTH_TOKEN’] to get the token (see Custom HTTP Header in Django)

There are more things to consider like CSRF token or JWT.

See this site for a complete example https://jee-appy.blogspot.com/2018/02/make-rest-api-django.html. Be warned, it use old version of django.

Leave a comment