LoginSignup
4
5

More than 5 years have passed since last update.

Django RESTFrameworkの勉強(1)

Last updated at Posted at 2019-05-04

Amazon Linux release 2 (Karoo)

準備

# 作業ディレクトリ作成
cd
mkdir -p work
cd work

# 仮想環境作成
python3 -m venv ~/py37/

# 仮想環境に切り替え
source ~/py37/bin/activate

# Django、DangoRestFrameworkをインストール
pip install django
pip install djangorestframework

# プロジェクト作成
django-admin startproject djangorestframework_sample
cd djangorestframework_sample
django-admin startapp restapi001

次に、djangorestframework_sample/settings.pyを開き、 INSTALLED_APPSに、「'rest_framework',」を追加

vi settings.py
djangorestframework_sample/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]

Viewの実装(クラスベースと関数ベース)

cd restapi001
vi views.py
restapi001/views.py
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response

from rest_framework import status


class HelloWorld(APIView):
    """
    クラスベースのAPIView
    ・HTTPのメソッドがクラスのメソッドになるので、わかりやすい
    """
    def get(self, request, format=None):
        return Response({"message": "Hello World!!"},
            status=status.HTTP_200_OK)

    def post(self, request, format=None):
        request_data = request.data
        return Response({"message": request_data["message"]},
            status=status.HTTP_201_CREATED)


@api_view(['GET', 'POST'])
def hello_world(request):
    """
    関数ベースのAPIView
    ・実装がシンプルで、読みやすい
    ・GET, POSTなどを関数内で分岐させないといけない
    """
    if request.method == 'GET':
        return Response({"message": "Hello function base APIView GET!!"},
            status=status.HTTP_200_OK)
    elif request.method == 'POST':
        if request.data:
            request_data = request.data
            return Response({"message": request_data["message"]},
                status=status.HTTP_201_CREATED)

ルーティングの実装

vi urls.py
restapi001/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.hello_world, name='hello'),
    path('hello', views.HelloWorld.as_view(), name='test-get')
]

restapi001/urls.pyのファイルを読み込むためdjangorestframework_sample/urls.pyにコードを実装

cd ..
cd djangorestframework_sample
vi urls.py
djangorestframework_sample/urls.py
from django.urls import path, include

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

動作確認

python manage.py runserver

ブラウザを起動し、http://127.0.0.1:8000/restapi001
1.PNG

関数ベースのAPIViewの動作確認 -以下のように入力してPOSTをクリック-
2.PNG

3.PNG

クラスベースのAPIViewの動作確認
http://127.0.0.1:8000/restapi001/hello にアクセス
4.PNG

以下のように入力してPOSTをクリック
5.PNG
6.PNG

参考URL
Django REST Framework -Views-
Django REST Framework -View の使い方をまとめてみた-
Djangoのfunction based viewとclass based viewの違い・メリット・デメリットを調べた

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5