So far, we've seen an example of a web application that returns an HTML response.
Next, let's create an example that returns JSON as the backend of an iOS / Android app. You could introduce a module that creates a REST API, like Django REST framework, but I'll write it myself first.
Create an application called api under the mybook project.
$ python manage.py startapp api
The following files have been created under the mybook project directory.
mybook/
api/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
Basically, it uses the json module to convert a Python dictionary object to JSON.
import json
data = {'id': 1, 'name': 'hoge'}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
However, since Python dictionaries are in random order, the contents of JSON are also in random order.
So we use collections.OrderedDict ordered dictionary.
Note that OrderedDict can be used from Python 2.7, so if the server environment is Python 2.6 or lower, use ordereddict.
ʻApi / views.py` looks like this:
import json
from collections import OrderedDict
from django.http import HttpResponse
from cms.models import Book
def render_json_response(request, data, status=None):
"""Return response in JSON"""
json_str = json.dumps(data, ensure_ascii=False, indent=2)
callback = request.GET.get('callback')
if not callback:
callback = request.POST.get('callback') #For JSONP with POST
if callback:
json_str = "%s(%s)" % (callback, json_str)
response = HttpResponse(json_str, content_type='application/javascript; charset=UTF-8', status=status)
else:
response = HttpResponse(json_str, content_type='application/json; charset=UTF-8', status=status)
return response
def book_list(request):
"""Returns JSON of books and impressions"""
books = []
for book in Book.objects.all().order_by('id'):
impressions = []
for impression in book.impressions.order_by('id'):
impression_dict = OrderedDict([
('id', impression.id),
('comment', impression.comment),
])
impressions.append(impression_dict)
book_dict = OrderedDict([
('id', book.id),
('name', book.name),
('publisher', book.publisher),
('page', book.page),
('impressions', impressions)
])
books.append(book_dict)
data = OrderedDict([ ('books', books) ])
return render_json_response(request, data)
render_json_response () also supports JSONP. It can be applied not only to the API of smartphones but also to get JSON with Ajax of Javascript.
Create a new file called ʻapi / urls.py` and write as follows.
from django.urls import path
from api import views
app_name = 'api'
urlpatterns = [
#Books
path('v1/books/', views.book_list, name='book_list'), #List
]
Include this ʻapi / urls.py in your project's
mybook / urls.py`.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('cms/', include('cms.urls')),
path('api/', include('api.urls')), #Add here
path('admin/', admin.site.urls),
]
You need to tell your project that you have installed the api application.
There is no model or template, so it works without it, but let's do it.
When I open ʻapi / apps.py, a class called ApiConfig is defined. Add this to the end of ʻINSTALLED_APPS
in mybook / settings.py
with the string 'api.apps.ApiConfig',
.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cms.apps.CmsConfig', #cms application
'api.apps.ApiConfig', #api application
'bootstrap4', # django-bootstrap4
]
Then, open the following URL in your browser.
http://127.0.0.1:8000/api/v1/books/
The result is as follows.
{
"books": [
{
"id": 1,
"name": "Getting Started with Django",
"publisher": "GeekLab.Nagano",
"page": 100,
"impressions": [
{
"id": 1,
"comment": "Ah ah\r\n good"
},
{
"id": 2,
"comment": "Uuu\r\n yeah"
},
{
"id": 4,
"comment": "comment\r\n."
}
]
},
{
"id": 2,
"name": "Book 2",
"publisher": "GeekLab.Nagano",
"page": 200,
"impressions": []
}
]
}
JSON is fine when sending data to an iOS / Android app, but what if you want to receive data?
When receiving in JSON, you can extract the JSON string from raw_post_data in the request.
import json
def xxxx_post(request):
python_obj = json.loads(request.raw_post_data) #Ask to POST so that the Body of Request is directly a JSON string
:
If you only want to create a smartphone API, you can use the functions of Django's management site to input data and write only the API part. You can easily create a backend for your smartphone.
If you want to create an API in earnest, please consider introducing Django REST framework.
This is the end of this course.
After this course, you can deepen your understanding by trying the official tutorials 1 to 7.
Recommended Posts