Django REST frameworkチュートリアル

公式のQuick Startからチュートリアルへ。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
$ mkdir tutorial
$ cd tutorial
$ django-admin startproject tutorial .
$ cd tutorial
$ django-admin startapp quickstart
$ pwd
/work/tutorial/tutorial
$ cd ..
$ find .
.
./manage.py
./tutorial
./tutorial/__init__.py
./tutorial/asgi.py
./tutorial/quickstart
./tutorial/quickstart/__init__.py
./tutorial/quickstart/admin.py
./tutorial/quickstart/apps.py
./tutorial/quickstart/migrations
./tutorial/quickstart/migrations/__init__.py
./tutorial/quickstart/models.py
./tutorial/quickstart/tests.py
./tutorial/quickstart/views.py
./tutorial/settings.py
./tutorial/urls.py
./tutorial/wsgi.py
$ ./manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
$ ./manage.py createsuperuser --email admin@example.com --username admin
Password: ********
Password (again): ********
Superuser created successfully.

Serializers

Serializertutorial/quickstart/serializers.py)を定義。
SerializerはデータをPythonデータ型に変換し、JSONなどのコンテンツタイプにレンダリングする処理を担う。
既定のクラスを継承して実装する。ここでは主キーフィールドの変わりにurlフィールドを使用するHyperlinkedModelSerializerを使用している。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.contrib.auth.models import User, Group
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']

Views

Viewtutorial/quickstart/views.py)を定義。
ViewSetsでモデルのCRUD操作を暗黙的に実装している。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer

URLs

urltutorial/urls.py)を定義。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.urls import include, path
from rest_framework import routers
from tutorial.quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Pagination

settingstutorial/settings.py)をカスタマイズ。

  • SECRET_KEYを環境変数で定義する
  • INSTALL_APPSでrest_frameworkを追加する
  • Pagenation(次のページ)を有効化する
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']

…略…

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}

アクセス

Viewとしてusersgroupsが定義されている

1
2
3
4
5
$ curl -H 'Accept: application/json; indent=4' -u admin:adminadmin http://127.0.0.1:8000/
{
"users": "http://127.0.0.1:8000/users/",
"groups": "http://127.0.0.1:8000/groups/"
}

Django REST framework quickstart width=640

Paginationを設定したので、応答にnextpreviousが追加されている。アイテム数が少ないので、値はnull。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ curl -H 'Accept: application/json; indent=4' -u admin:adminadmin http://127.0.0.1:8000/users/
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin",
"email": "admin@example.com",
"groups": []
}
]
}
$ curl -H 'Accept: application/json; indent=4' -u admin:adminadmin http://127.0.0.1:8000/groups/
{
"count": 0,
"next": null,
"previous": null,
"results": []
}

Django REST framework quickstart width=640

Django REST framework quickstart width=640