【Python＋Django＋Docker＋VS Code】APIでJson取得しJson形式を返却する

環境メモ
⭐️macOS Monterey
⭐️Python 3.11.1
⭐️Django 4.1.6
⭐️Visual Studio Code 1.75.0 ←Mac OS版
⭐️Docker desktop 4.11.1 ←Mac OS版


## 1.環境構築

下記で、環境を作成する。
Djangoのプロジェクト (project) を作成し、Djangoのアプリケーションを作成します。

https://qiita.com/nonkapibara/items/32b4bbdc5510e2db0586


新規作成したDjangoのプロジェクトの`urls.py`

```urls.py
from django.contrib import admin
from django.urls import path, include

# XXXXは、新規作成したDjangoのアプリケーションのurls
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('XXXX.urls'))
]
```

## 2.urlpatternsを設定する

新規作成したDjangoのアプリケーションのurlsに以下のurlpatternsを設定します。

```urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('non/books/', views.func_books, name='books')
]
```

## 3.viewを設定する

新規作成したDjangoのアプリケーションのviewsにAPIでJson取得しJson形式を返却するコードを実装する

```views.py
# from django.shortcuts import render
from nonDjangoApp3.settings import BASE_DIR
import json
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def func_books(request):
    if request.method == 'POST':
        # JSON文字列
        result_data = json.loads(request.body)

        ### book no 取得 ###
        # book_no = result_data.get('bookNo')

        ### bookList no ###
        # book_list = result_data.get('bookList')
        # no = book_list[0]['no']

        ### userDataList name ###
        # user_data_list = book_list[0]['userDataList']
        # name = user_data_list[2]['name']

        ### bookList no 一括取得 ###
        name = ((result_data.get('bookList'))[2]['userDataList'])[2]['name']

        json_data = {'name': name}
        return JsonResponse(json_data, safe=False)
    else:
        # print('get')
        json_data = {'message': 'GETです'}
        return JsonResponse(json_data, safe=False)

```

## 4.APIリクエストを実行する

ここでは、VS CodeのREST ClientでAPIテストしました。
![スクリーンショット 2023-02-18 18.12.22.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/93155/fd378ec1-17eb-af49-8e5a-a0309528e057.png)


```book.rest
POST http://127.0.0.1:8000/non/books/ HTTP/1.1
content-type: application/json

  {
    "bookNo": "bookNo1",
    "bookName": "bookName1",
    "bookColor": "yellow",
    "bookList": [
      {
        "no": 1,
        "noName": "noNameA1",
        "total": 100,
        "userDataList": [
          {
            "id": 1,
            "name": "name1",
            "amount": 1001
          },
          {
            "id": 2,
            "name": "name2",
            "amount": 1002
          },
          {
            "id": 3,
            "name": "name3",
            "amount": 1003
          },
          {
            "id": 4,
            "name": "name4",
            "amount": 1004
          }
        ],
        "pageList": [
          {
            "page": 1,
            "pageName": "pageName1",
            "total": 1000,
            "picDataList": [
              {
                "picId": 11,
                "picName": "picName11",
                "picAmount": 1101
              },
              {
                "picId": 12,
                "picName": "picName12",
                "picAmount": 1102
              },
              {
                "picId": 13,
                "picName": "picName13",
                "picAmount": 1103
              },
              {
                "picId": 14,
                "picName": "picName14",
                "picAmount": 1104
              },
              {
                "picId": 15,
                "picName": "picName15",
                "picAmount": 1105
              }
            ]
          }
        ]
      },
      {
        "no": 2,
        "noName": "noNameA2",
        "total": 200,
        "userDataList": [
          {
            "id": 21,
            "name": "name21",
            "amount": 21001
          },
          {
            "id": 22,
            "name": "name22",
            "amount": 21002
          },
          {
            "id": 23,
            "name": "name23",
            "amount": 21003
          },
          {
            "id": 24,
            "name": "name24",
            "amount": 21004
          }
        ],
        "pageList": [
          {
            "page": 21,
            "pageName": "pageName21",
            "total": 2000,
            "picDataList": [
              {
                "picId": 21,
                "picName": "picName21",
                "picAmount": 2101
              },
              {
                "picId": 22,
                "picName": "picName22",
                "picAmount": 2102
              },
              {
                "picId": 23,
                "picName": "picName23",
                "picAmount": 2103
              },
              {
                "picId": 24,
                "picName": "picName24",
                "picAmount": 2104
              },
              {
                "picId": 25,
                "picName": "picName25",
                "picAmount": 2105
              }
            ]
          }
        ]
      },
      {
        "no": 3,
        "noName": "noNameA3",
        "total": 300,
        "userDataList": [
          {
            "id": 31,
            "name": "name31",
            "amount": 31001
          },
          {
            "id": 32,
            "name": "name32",
            "amount": 31002
          },
          {
            "id": 33,
            "name": "name33",
            "amount": 31003
          },
          {
            "id": 34,
            "name": "name34",
            "amount": 31004
          }
        ],
        "pageList": [
          {
            "page": 31,
            "pageName": "pageName31",
            "total": 3000,
            "picDataList": [
              {
                "picId": 31,
                "picName": "picName31",
                "picAmount": 3101
              },
              {
                "picId": 32,
                "picName": "picName32",
                "picAmount": 3102
              },
              {
                "picId": 33,
                "picName": "picName33",
                "picAmount": 3103
              },
              {
                "picId": 34,
                "picName": "picName34",
                "picAmount": 3104
              },
              {
                "picId": 35,
                "picName": "picName35",
                "picAmount": 3105
              }
            ]
          }
        ]
      }
    ]
  }

```

受信結果
![スクリーンショット 2023-02-18 18.16.35.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/93155/662b8666-b9dd-d0d3-8ed7-51fae10177d4.png)

完成！！




VS CodeのREST ClientでAPIテストする方法は、こちらに記載しています。

https://qiita.com/nonkapibara/items/83bcd01c4e32c03d13e7