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.
- You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth
- Django queryset exclude() with multiple related field clauses
- Emptying the database through Django's `manage.py`
- Libmysqlclient.18.dylib image not found when using MySQL from Django on OS X
0👍
You should go with Django Rest Framework but if you want to do it yourself then:
- 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)
-
If plain name/value pair is sent, then use request.POST or request.GET
-
Use JsonResponse to send the response
-
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.
- Minimize the list filter in django-admin
- Unknown command: shell_plus and –settings
- Python logging to multiple files
- Registering Django system checks in AppConfig's ready() method
- Pycharm (Python IDE) doesn't auto complete Django modules