How to build a json REST API in django (without Django REST framework)

你。 提交于 2020-06-25 17:07:41

问题


Preface

I have a django project. I've wired it up so it serves a bunch of views for a bunch of models. Now I want to add an endpoint which just dumps a good fraction of the database out as json.

The way I would assume you do this is add a URL to a view class / method which returns a HTTPResponseObject full of json. Unfortunately, after quite a bit of googling, all I can find are references to Django REST framework. This is the sort of thing you would think Django would provide internally not as part of an external plugin library. But searching the django docs doesn't yield an immediate answer -- I don't think there are any docs about how to build an endpoint which just serves a bunch of json.

Questions:

  • Do I really need "Django REST framework" to serve json in django?
  • Did I overlook docs in Django for serving json?
  • What is the canonical way to serve json in a django project?

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/46736881/how-to-build-a-json-rest-api-in-django-without-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!