Getting Started with Python Django (6)

Make a smartphone API

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.

Creating an api application

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

View that returns JSON

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.

URL that returns JSON

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),
]

Addition to INSTALLED_APPS

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
]

Check the result

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": []
    }
  ]
}

Receiving data from iOS / Android apps

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
      :

Summary of smartphone API

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.

Finally

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

Getting Started with Python Django (4)
Getting Started with Python Django (3)
Getting Started with Python Django (6)
Getting Started with Python Django (5)
Django 1.11 started with Python3.6
1.1 Getting Started with Python
Getting Started with Python
Getting Started with Django 1
Getting Started with Python
Getting Started with Django 2
Getting Started with Python Functions
Getting Started with Django with PyCharm
Python3 | Getting Started with numpy
Getting Started with Python responder v2
Getting Started with Python Web Applications
Getting Started with Python for PHPer-Classes
Getting Started with Python Basics of Python
Getting Started with Python Genetic Algorithms
Getting started with Python 3.8 on Windows
Getting Started with Python for PHPer-Functions
Getting Started with python3 # 1 Learn Basic Knowledge
Getting Started with Golang 2
Getting Started with Python Web Scraping Practice
Getting started with apache2
Getting Started with Optimization
Getting Started with Python Web Scraping Practice
Getting Started with Golang 3
Getting Started with Numpy
Getting started with Spark
Getting Started with Pydantic
Getting Started with Golang 4
Getting Started with Jython
Getting Started with Heroku-Viewing Hello World in Python Django with Raspberry PI 3
Getting started with Python with 100 knocks on language processing
Django Getting Started Part 2 with eclipse Plugin (PyDev)
Getting started with AWS IoT easily in Python
Django Getting Started Part 3 about Python3 & MySQL Connector
Materials to read when getting started with Python
Settings for getting started with MongoDB in python
Translate Getting Started With TensorFlow
Do Django with CodeStar (Python3.6.8, Django2.2.9)
Getting Started with Tkinter 2: Buttons
Get started with Django! ~ Tutorial ⑤ ~
Getting Started with Go Assembly
Django Getting Started: 2_ Project Creation
Django Getting Started: 1_Environment Building
Do Django with CodeStar (Python3.8, Django2.1.15)
Python3 + Django ~ Mac ~ with Apache
Django Getting Started: 4_MySQL Integration
Django Getting Started: 3_Apache integration
Get started with Django! ~ Tutorial ④ ~
Get started with Django! ~ Tutorial ⑥ ~
Get started with Python! ~ ② Grammar ~
Getting Started with python3 # 2 Learn about types and variables
Getting Started with Google App Engine for Python & PHP
started python
Get started with Python! ~ ① Environment construction ~
Link to get started with python
Getting Started with Git (1) History Storage
Getting started with Sphinx. Generate docstring with Sphinx
Getting Started with Sparse Matrix with scipy.sparse