django REST framework

  • The Web browsable API is a huge usability win for your developers.
  • Authentication policies including packages for OAuth1a and OAuth2.
  • Serialization that supports both ORM and non-ORM data sources.
  • Customizable all the way down - just use regular function-based views if you don’t need the more powerful features.
  • Extensive documentation, and great community support.
  • Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite.
  • Webブラウジング可能なAPIによるユーザビリティ
  • OAuth1aとOuth2のための認証ポリシーを含む
  • ORMとnon-ORMの各データソースのシリアライズをサポート
  • 端から端までカスタマイズ可能
  • 広範囲のドキュメントとコミュニティサポート
  • さまざまな国際的企業で利用されている

Django REST framework width=640

BLACK LIVES MATTERやってる(2020/6/18)

Requirements

REST framework requires the following:

Python (3.5, 3.6, 3.7, 3.8)
Django (1.11, 2.0, 2.1, 2.2, 3.0)
We highly recommend and only officially support the latest patch release of each Python and Django series.

The following packages are optional:

coreapi (1.32.0+) - Schema generation support.
Markdown (3.0.0+) - Markdown support for the browsable API.
Pygments (2.4.0+) - Add syntax highlighting to Markdown processing.
django-filter (1.0.1+) - Filtering support.
django-guardian (1.1.1+) - Object level permissions support.

これを元にrequirement.txtを作成。

1
djangorestframework

Django REST frameworkのインストール

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ pip install -r requirements.txt
Collecting djangorestframework
Downloading djangorestframework-3.11.0-py3-none-any.whl (911 kB)
|████████████████████████████████| 911 kB 3.2 MB/s
Collecting django>=1.11
Downloading Django-3.0.7-py3-none-any.whl (7.5 MB)
|████████████████████████████████| 7.5 MB 10.5 MB/s
Collecting sqlparse>=0.2.2
Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB)
|████████████████████████████████| 40 kB 7.7 MB/s
Collecting asgiref~=3.2
Downloading asgiref-3.2.9-py3-none-any.whl (19 kB)
Requirement already satisfied: pytz in /usr/local/lib/python3.8/site-packages (from django>=1.11->djangorestframework->-r requirements.txt (line 1)) (2019.3)
Installing collected packages: sqlparse, asgiref, django, djangorestframework
Successfully installed asgiref-3.2.9 django-3.0.7 djangorestframework-3.11.0 sqlparse-0.3.1

Exampleで基本的な動作を見る

プロジェクト作成

  1. django-adminコマンドでexampleプロジェクトを作成
  2. manage.py migrateを実行
  3. manage.py createsuperuserでrootアカウント作成
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
$ django-admin startproject example .
$ tree .
.
├── README.md
├── docker-compose.yml
├── example
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── requirements.txt

1 directory, 9 files

$ ./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
Username (leave blank to use 'root'):
Email address:
Password: ********
Password (again): ********
Superuser created successfully.

settings.pyのカスタマイズ

INSTALLED_APPSrest_frameworkを追加し、REST_FRAMEWORKで基本設定を行う。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]

REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}

url.pyのカスタマイズ

Example用のAPIをカスタマイズ。

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
from django.urls import path, include
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets, routers

# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'is_staff']


# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer


# Routers provide a way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)


# 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'))
]

APIのテスト

1
2
3
4
5
6
7
8
9
10
11
$ ./manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
June 17, 2020 - 15:50:19
Django version 3.0.7, using settings 'example.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[17/Jun/2020 15:50:42] "GET / HTTP/1.1" 200 47
[17/Jun/2020 15:50:49] "GET /users/ HTTP/1.1" 200 138

作成済のrootアカウントを閲覧できるか確認する。

1
2
3
4
5
6
7
8
9
10
11
12
13
$ curl -H 'Accept: application/json; indent=4' -u root:rootroot http://127.0.0.1:8000/
{
"users": "http://127.0.0.1:8000/users/"
}
$ curl -H 'Accept: application/json; indent=4' -u root:rootroot http://127.0.0.1:8000/users/
[
{
"url": "http://127.0.0.1:8000/users/1/",
"username": "root",
"email": "",
"is_staff": true
}
]

ユーザを追加する。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ curl -X POST -d username=new -d email=new@example.com -d is_staff=false -H 'Accept: application/json; indent=4' -u root:rootroot http://127.0.0.1:8000/users/
{
"url": "http://127.0.0.1:8000/users/2/",
"username": "new",
"email": "new@example.com",
"is_staff": false
}
$ curl -H 'Accept: application/json; indent=4' -u root:rootroot http://127.0.0.1:8000/users/
[
{
"url": "http://127.0.0.1:8000/users/1/",
"username": "root",
"email": "",
"is_staff": true
},
{
"url": "http://127.0.0.1:8000/users/2/",
"username": "new",
"email": "new@example.com",
"is_staff": false
}
]

runserverは127.0.0.1で待ち受けるので、コンテナ外からアクセスできるように0.0.0.0で待ち受ける。

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
$ ./manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
June 17, 2020 - 16:12:22
Django version 3.0.7, using settings 'example.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[17/Jun/2020 16:12:38] "GET / HTTP/1.1" 200 5322
[17/Jun/2020 16:12:38] "GET /static/rest_framework/css/bootstrap-tweaks.css HTTP/1.1" 200 3385
[17/Jun/2020 16:12:38] "GET /static/rest_framework/js/csrf.js HTTP/1.1" 200 1719
[17/Jun/2020 16:12:38] "GET /static/rest_framework/css/prettify.css HTTP/1.1" 200 817
[17/Jun/2020 16:12:38] "GET /static/rest_framework/js/prettify-min.js HTTP/1.1" 200 13632
[17/Jun/2020 16:12:38] "GET /static/rest_framework/css/bootstrap.min.css HTTP/1.1" 200 121457
[17/Jun/2020 16:12:38] "GET /static/rest_framework/css/default.css HTTP/1.1" 200 1131
[17/Jun/2020 16:12:38] "GET /static/rest_framework/js/bootstrap.min.js HTTP/1.1" 200 39680
[17/Jun/2020 16:12:38] "GET /static/rest_framework/js/ajax-form.js HTTP/1.1" 200 3597
[17/Jun/2020 16:12:38] "GET /static/rest_framework/js/default.js HTTP/1.1" 200 1268
[17/Jun/2020 16:12:38] "GET /static/rest_framework/js/jquery-3.4.1.min.js HTTP/1.1" 200 88145
[17/Jun/2020 16:12:39] "GET / HTTP/1.1" 200 5322
[17/Jun/2020 16:12:39] "GET /static/rest_framework/img/grid.png HTTP/1.1" 200 1458
Not Found: /favicon.ico
[17/Jun/2020 16:12:39] "GET /favicon.ico HTTP/1.1" 404 3137
[17/Jun/2020 16:13:02] "GET /users/ HTTP/1.1" 200 5886
[17/Jun/2020 16:13:03] "GET /static/rest_framework/css/bootstrap-tweaks.css HTTP/1.1" 304 0
[17/Jun/2020 16:13:03] "GET /static/rest_framework/css/default.css HTTP/1.1" 304 0
[17/Jun/2020 16:13:03] "GET /static/rest_framework/css/bootstrap.min.css HTTP/1.1" 304 0
[17/Jun/2020 16:13:03] "GET /static/rest_framework/css/prettify.css HTTP/1.1" 304 0
[17/Jun/2020 16:13:03] "GET /static/rest_framework/js/jquery-3.4.1.min.js HTTP/1.1" 304 0
[17/Jun/2020 16:13:03] "GET /static/rest_framework/js/csrf.js HTTP/1.1" 304 0
[17/Jun/2020 16:13:03] "GET /static/rest_framework/js/ajax-form.js HTTP/1.1" 304 0
[17/Jun/2020 16:13:03] "GET /static/rest_framework/js/default.js HTTP/1.1" 304 0
[17/Jun/2020 16:13:03] "GET /static/rest_framework/js/prettify-min.js HTTP/1.1" 304 0
[17/Jun/2020 16:13:03] "GET /static/rest_framework/js/bootstrap.min.js HTTP/1.1" 304 0
[17/Jun/2020 16:13:03] "GET /static/rest_framework/img/grid.png HTTP/1.1" 304 0

Django REST framework example width=640

Django REST framework example width=640

管理画面

from django.contrib import adminでインポートし、urlpatternsにpath('admin/', admin.site.urls),を追加する。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from django.contrib import admin
#from django.urls import path

#urlpatterns = [
# path('admin/', admin.site.urls),
#]

from django.urls import path, include
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets, routers

…中略…

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

http://localhost:8000/admin/から管理機能にアクセスできる。

Django REST framework example width=640

Django REST framework example width=640