プリンキピア

第11章Webアプリケーション開発

Setting Up the Django REST APIsDjangoのREST APIの設定

Previously, you installed the Django REST Framework, which provides a toolkit to build APIs. In this section, you’ll create the serializers, View functions, and routers required for the API.
すでに、APIを構築するためのツールキットを提供するDjango REST Frameworkをインストールした。この項では、APIに必要なシリアライザー、View関数、ルーターを作成する。
Creating the Serializersシリアライザーの作成
The next step is to implement two serializers, one for the Category model and one for the TodoList model. A serializer is a tool to control response outputs and convert complex data into content, such as JSON. In the todo/ directory, create the file, serializers.py, and add the code shown in the code snippet that follows. The serializer classes inherit from serializers.ModelSerializer because this class creates the serializer, with fields corresponding to the Model fields defined earlier. Each serializer specifies the Model to work with and the fields to be included in the JSON object, which are all fields.
英語のヒント
次に、Categoryモデル用とTodoListモデル用の、2つのシリアライザーを実装する。シリアライザーは、応答の出力を制御し、複雑なデータをJSONなどの内容へ変換するツールである。todo/ディレクトリにserializers.pyファイルを作り、次のコード例を追加する。シリアライザーのクラスは、serializers.ModelSerializerを継承する。このクラスが、先に定義したModelのフィールドに対応するフィールドを持つシリアライザーを作るためである。各シリアライザーは、対象となるModelと、JSONオブジェクトに含めるフィールドを指定する。ここでは、すべてのフィールドを含める。
# todo/serializers.py

from rest_framework import serializers
from .models import TodoList, Category

class CategorySerializer(serializers.ModelSerializer):
  class Meta:
    model = Category
    fields = "__all__"

class TodoSerializer(serializers.ModelSerializer):
  class Meta:
    model = TodoList
    fields = "__all__"
Creating the ViewViewの作成
After you create each serializer, the next step is to create a corresponding View function for both the Category serializer and the Todo serializer. To do this, open todo/views.py and add the code shown in the code snippet that follows. The viewsets class, which provides a default implementation of the CRUD operations, is imported from rest_framework. The CategoryView and TodoView classes provide a queryset of categories and todo items, respectively. They also specify the serializer_class defined in the previous section.
英語のヒント
各シリアライザーを作成したら、次に、CategoryシリアライザーとTodoシリアライザーのそれぞれに対応するView関数を作成する。そのために、todo/views.pyを開き、次のコード例を追加する。CRUD操作の標準的な実装を提供するviewsetsクラスを、rest_frameworkからインポートする。CategoryViewクラスとTodoViewクラスは、それぞれカテゴリーとtodo項目のquerysetを提供する。また、前の項で定義したserializer_classも指定する。
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render,redirect
from rest_framework import viewsets
from .serializers import TodoSerializer, CategorySerializer
from .models import TodoList, Category
import datetime

# Create your views here.

class CategoryView(viewsets.ModelViewSet):
  queryset = Category.objects.all()
  serializer_class = CategorySerializer

class TodoView(viewsets.ModelViewSet):
  queryset = TodoList.objects.all()
  serializer_class = TodoSerializer
Creating the Routersルーターの作成
The next step is to create the routers that provide URL paths for the API. To do this, open the todo/urls.py file and add the code shown in the code snippet that follows:
次に、APIのURLパスを提供するルーターを作成する。そのために、todo/urls.pyファイルを開き、次のコード例を追加する。
from django.urls import path, include
#from todo import views as todo_views
from rest_framework import routers
from todo.views import *

router = routers.DefaultRouter()
router.register(r'categories', CategoryView, basename='Categories')
router.register(r'todos', TodoView, basename='Todos')

urlpatterns = [
  path('', index, name="TodoList"),
  path(r'api/', include(router.urls)),
]
Once you complete this step, launch the Django server using the following command:
この手順が完了したら、次のコマンドでDjangoサーバーを起動する。
$ python manage.py runserver
To access the API, launch a browser and navigate to http://127.0.0.1:8000/api/. As shown in Figure 11.21, you should see two API paths listed, one for categories and another for todo items.
APIへアクセスするには、ブラウザーを起動し、http://127.0.0.1:8000/api/へ移動する。図11.21のように、カテゴリー用とtodo項目用の、2つのAPIパスが表示されるはずである。
Figure 11.21

rendered in Django, a registered trademark of the Django Software Foundation; attribution: Copyright Rice University, OpenStax, under CC BY 4.0 license · CC BY 4.0 · Source出典

Figure 11.21 Once the URL paths for the API are created, two API paths are listed—one path for categories and the other for todo. (rendered in Django, a registered trademark of the Django Software Foundation; attribution: Copyright Rice University, OpenStax, under CC BY 4.0 license)
図11.21 APIのURLパスを作成すると、カテゴリー用とtodo用の2つのAPIパスが表示される。(Djangoで表示。DjangoはDjango Software Foundationの登録商標。出典:Copyright Rice University, OpenStax、CC BY 4.0ライセンス)
Todo items are dependent on categories. To perform CRUD operations on the Category table, click on the categories API path, as shown in Figure 11.22.
todo項目は、カテゴリーに依存する。Categoryテーブルに対するCRUD操作を行うには、図11.22のようにcategoriesのAPIパスをクリックする。
Figure 11.22

rendered in Django, a registered trademark of the Django Software Foundation; attribution: Copyright Rice University, OpenStax, under CC BY 4.0 license · CC BY 4.0 · Source出典

Figure 11.22 The API path can be used to perform CRUD operations on the Category table. (rendered in Django, a registered trademark of the Django Software Foundation; attribution: Copyright Rice University, OpenStax, under CC BY 4.0 license)
図11.22 このAPIパスを使って、Categoryテーブルに対するCRUD操作を行える。(Djangoで表示。DjangoはDjango Software Foundationの登録商標。出典:Copyright Rice University, OpenStax、CC BY 4.0ライセンス)
Once you access the Category List page, enter a category name in the field near the bottom of the page and click the Post button to save it. You can add additional category names. Once you save each name using the Post button, the categories will appear in JSON format, as illustrated in Figure 11.23.
Category Listページへアクセスしたら、ページ下部付近の欄にカテゴリー名を入力し、Postボタンをクリックして保存する。カテゴリー名は、さらに追加できる。各名前をPostボタンで保存すると、図11.23のように、カテゴリーがJSON形式で表示される。
Figure 11.23

rendered in Django, a registered trademark of the Django Software Foundation; attribution: Copyright Rice University, OpenStax, under CC BY 4.0 license · CC BY 4.0 · Source出典

Figure 11.23 The Category List is created in JSON format after saving category names. (rendered in Django, a registered trademark of the Django Software Foundation; attribution: Copyright Rice University, OpenStax, under CC BY 4.0 license)
図11.23 カテゴリー名を保存すると、Category ListがJSON形式で作られる。(Djangoで表示。DjangoはDjango Software Foundationの登録商標。出典:Copyright Rice University, OpenStax、CC BY 4.0ライセンス)
To ensure that categories can be updated or deleted as needed, the primary key, which is “id”, must be included in the API path (e.g., /api/categories/{id}/). For example, to update or delete the category with id=3, the API path is /api/categories/3/. As shown in Figure 11.24, once this category is pulled up on the Category Instance page, the DELETE button is visible at the top to delete the category. If the category needs to be updated, the PUT button visible near the bottom can be used for updates.
英語のヒント
必要に応じてカテゴリーを更新・削除できるようにするには、APIパスに主キーである“id”を含める必要がある(例:/api/categories/{id}/)。たとえば、id=3のカテゴリーを更新または削除する場合、APIパスは/api/categories/3/となる。図11.24のように、このカテゴリーをCategory Instanceページに表示すると、上部に、そのカテゴリーを削除するためのDELETEボタンが現れる。カテゴリーを更新する必要がある場合は、下部付近のPUTボタンを使える。
Figure 11.24

rendered in Django, a registered trademark of the Django Software Foundation; attribution: Copyright Rice University, OpenStax, under CC BY 4.0 license · CC BY 4.0 · Source出典

Figure 11.24 The Category Instance page provides DELETE and PUT buttons, which, respectively, can be used to delete or update a category. (rendered in Django, a registered trademark of the Django Software Foundation; attribution: Copyright Rice University, OpenStax, under CC BY 4.0 license)
図11.24 Category Instanceページには、カテゴリーの削除と更新にそれぞれ使える、DELETEボタンとPUTボタンがある。(Djangoで表示。DjangoはDjango Software Foundationの登録商標。出典:Copyright Rice University, OpenStax、CC BY 4.0ライセンス)
Next, navigate back to the API root. Click on the todos API path to see, as outlined in Figure 11.25, that a Todo item has a Category field that appears as a drop-down list of categories. The CRUD operations also can be performed on the TodoList table. This will be done next through the user interface via templates.
次に、APIのルートへ戻る。todosのAPIパスをクリックすると、図11.25のように、Todo項目にはカテゴリーのドロップダウンリストとして表示されるCategoryフィールドがあることを確認できる。TodoListテーブルに対してもCRUD操作を行える。次は、テンプレートを用いた利用者インターフェースを通じて、その操作を行う。
Figure 11.25

rendered in Django, a registered trademark of the Django Software Foundation; attribution: Copyright Rice University, OpenStax, under CC BY 4.0 license · CC BY 4.0 · Source出典

Figure 11.25 After the routers are created, a Todo item has a Category field that appears as a drop-down list of categories, such as “Work” and “Personal.” (rendered in Django, a registered trademark of the Django Software Foundation; attribution: Copyright Rice University, OpenStax, under CC BY 4.0 license)
図11.25 ルーターを作成すると、Todo項目には、“Work”や“Personal”などのカテゴリーをドロップダウンリストで表示する、Categoryフィールドができる。(Djangoで表示。DjangoはDjango Software Foundationの登録商標。出典:Copyright Rice University, OpenStax、CC BY 4.0ライセンス)