Amplify + React/Redux アプリ開発 ~ バックエンド API ~

October 05, 2020

今回やること

今回は Amplify Framework + React/Redux を用いて以下のことをやります。

  • バックエンド API (API Gateway + Lambda) の作成
  • バックエンドのデプロイ

“Hello Amplify” というメッセージを返却するだけの API を作成・実行するところまでやってみます。

インストール

まずは Amplify CLI をインストールする必要があります。以下のコマンドでちゃちゃっとインストールしちゃいましょう。

npm install -g @aws-amplify/cli  

初期セットアップ

まずは create-react-app で React アプリを作りましょう。

$ create-react-app sample-app  
  
Creating a new React app in /home/ec2-user/AmplifyTest/sample-app.  
  
...  
  
Success! Created sample-app at /home/ec2-user/AmplifyTest/sample-app  
  
...  
  

今回は redux を利用するのでついでに必要なディレクトリを作成しておきます。

$ cd sample-app/  
$ cd sample-app/src/  
$ mkdir containers components actions utils reducers  
$ tree -L 1  
.  
├── actions  
├── App.css  
├── App.js  
├── App.test.js  
├── components  
├── containers  
├── index.css  
├── index.js  
├── logo.svg  
├── reducers  
├── serviceWorker.js  
├── setupTests.js  
└── utils  
  
5 directories, 8 files  

また、必要なライブラリをインストールします。

$ cd ..  
$ npm install react-redux redux react-router redux-thunk aws-amplify @aws-amplify/ui-react  
  
..  
  
+ redux-thunk@2.3.0  
+ redux@4.0.5  
+ react-router@5.2.0  
+ react-redux@7.2.1  
+ @aws-amplify/ui-react@0.2.23  
+ aws-amplify@3.3.3  
added 178 packages from 431 contributors and audited 1813 packages in 19.128s  
  
73 packages are looking for funding  
  run `npm fund` for details  
  
found 0 vulnerabilities  

次に、作業ディレクトリで amplify init コマンドを実行し、バックエンドの初期化を行います。

$ amplify init   
Scanning for plugins...  
Plugin scan successful  
Note: It is recommended to run this command from the root of your app directory  
? Enter a name for the project AmplifySampleApp  
? Enter a name for the environment dev  
? Choose your default editor: Emacs (via Terminal, Mac OS only)  
? Choose the type of app that you're building javascript  
Please tell us about your project  
? What javascript framework are you using react  
? Source Directory Path:  src  
? Distribution Directory Path: build  
? Build Command:  npm run-script build  
? Start Command: npm run-script start  
Using default provider  awscloudformation  
  
...  
  
CREATE_COMPLETE amplify-amplifysampleapp-dev-200823 AWS::CloudFormation::Stack Sun Oct 04 2020 20:08:54 GMT+0000 (Coordinated Universal Time)   
CREATE_COMPLETE DeploymentBucket                    AWS::S3::Bucket            Sun Oct 04 2020 20:08:51 GMT+0000 (Coordinated Universal Time)   
✔ Successfully created initial AWS cloud resources for deployments.  
✔ Initialized provider successfully.  
Initialized your environment successfully.  
  
Your project has been successfully initialized and connected to the cloud!  
  
Some next steps:  
"amplify status" will show you what you've added already and if it's locally configured or deployed  
"amplify add <category>" will allow you to add features like user login or a backend API  
"amplify push" will build all your local backend resources and provision it in the cloud  
"amplify console" to open the Amplify Console and view your project status  
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud  
  
Pro tip:  
Try "amplify add api" to create a backend API and then "amplify publish" to deploy everything  

これで準備は完了です。

API の作成

さて、早速 API を作ってみましょう。amplify add api コマンドで作成します。

$ amplify add api  
? Please select from one of the below mentioned services: REST  
? Provide a friendly name for your resource to be used as a label for this category in the project: helloApi  
? Provide a path (e.g., /book/{isbn}): /hello  
? Choose a Lambda source Create a new Lambda function  
? Provide a friendly name for your resource to be used as a label for this category in the project: helloApiLambda  
? Provide the AWS Lambda function name: helloApiLambda  
? Choose the runtime that you want to use: Python  
Only one template found - using Hello World by default.  
? Do you want to access other resources in this project from your Lambda function? No  
? Do you want to invoke this function on a recurring schedule? No  
? Do you want to configure Lambda layers for this function? No  
? Do you want to edit the local lambda function now? No  
Successfully added resource helloApiLambda locally.  
  
Next steps:  
Check out sample function code generated in <project-dir>/amplify/backend/function/helloApiLambda/src  
"amplify function build" builds all of your functions currently in the project  
"amplify mock function <functionName>" runs your function locally  
"amplify push" builds all of your local backend resources and provisions them in the cloud  
"amplify publish" builds all of your local backend and front-end resources (if you added hosting category) and provisions them in the cloud  
Succesfully added the Lambda function locally  
? Restrict API access No  
? Do you want to add another path? No  
Successfully added resource helloApi locally  
  
Some next steps:  
"amplify push" will build all your local backend resources and provision it in the cloud  
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud  

すると、amplify/backend/function/helloApiLambda/src/ 配下に Lambda 関数のソースコードが出来上がるのでそれを編集します。

amplify/backend/function/helloApiLambda/src/index.py
import json  
  
def handler(event, context):  
  print('received event:')  
  print(event)  
  response = {  
    'statusCode': 200,  
    'headers': {  
      'Access-Control-Allow-Origin': '*'  
    },  
    'body': json.dumps({ 'message': 'Hello Amplify' })  
  }  
  
  return response  

あとは amplify push コマンドで API をデプロイします。

$ amplify push  
✔ Successfully pulled backend environment dev from the cloud.  
  
Current Environment: dev  
  
| Category | Resource name  | Operation | Provider plugin   |  
| -------- | -------------- | --------- | ----------------- |  
| Function | helloApiLambda | Create    | awscloudformation |  
| Api      | helloApi       | Create    | awscloudformation |  
? Are you sure you want to continue? Yes  
Installing dependencies from Pipfile.lock (db4242)...  
  
✔ All resources are updated in the cloud  
  
REST API endpoint: https://xxxxxxxxxx.execute-api.us-west-2.amazonaws.com/dev  

これで API がデプロイされたので、試しに叩いてみましょう。

$ curl https://xxxxxxxxxx.execute-api.us-west-2.amazonaws.com/dev/hello  
{"message": "Hello Amplify"}  

良さそうですね。
次回は Github 連携、フロントの開発・デプロイまで進んでみたいと思います。


 © 2023, Dealing with Ambiguity