Django RESTFrameworkの勉強(1)

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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/208807/7e1ec780-446d-f3e0-5434-e28544730e94.png)

**関数ベースのAPIViewの動作確認 -以下のように入力してPOSTをクリック-**
![2.PNG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/208807/6baf17e4-e5f1-4035-b7f7-69de5f05f8d3.png)

![3.PNG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/208807/c9f2d160-f7a9-30d0-2881-2413cf1daeec.png)

**クラスベースのAPIViewの動作確認**
http://127.0.0.1:8000/restapi001/hello にアクセス
![4.PNG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/208807/2b741777-6b31-dcd1-bc3b-2a02c1fcb1be.png)

**以下のように入力してPOSTをクリック**
![5.PNG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/208807/45d13599-4c27-18b7-276d-555334c6f4b8.png)
![6.PNG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/208807/d7eab5ae-9704-0283-4ed2-58926bc79344.png)

**参考URL**
[Django REST Framework -Views-](https://www.django-rest-framework.org/api-guide/views/)
[Django REST Framework -View の使い方をまとめてみた-](http://note.crohaco.net/2018/django-rest-framework-view/)
[Djangoのfunction based viewとclass based viewの違い・メリット・デメリットを調べた](http://swiftfe0.hatenablog.com/entry/2019/02/26/181312)