How to create a Rest API using the serverless framework to use only AWS pay-per-use services, using nestjs as a development framework?
-
The basic need is that we need to create a Rest API using Serverless charge-only services.
-
The solution will be to define the project through a typical development of a service in nestjs with typescript where initially we will deploy on a local machine and then we will deploy to an AWS account using the Serverless Framework.
- Api Gateway
- Lamda Function
- DynamoDB
- Cloudwatch
- IAM Policys
- Nestjs Framework
- AWS account.
- IAM credentials. (Username and Password to enter the console).
- IAM access key pair. (Access Key ID and Secret Access Key).
Linux/Ubuntu:
- curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
- unzip awscliv2.zip
- sudo ./aws/install
-
- Download and run the AWS CLI MSI installer for Windows (64-bit):
- https://awscli.amazonaws.com/AWSCLIV2.msi - You can also run the msiexec command to run the MSI installer from PowerShell:
- msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi
Execute the command:
- aws configure
- AWS Access Key ID [None]: XXXXXXXXXXXXXXXXXXXX
- AWS Secret Access Key [None]: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
- Default region name [None]: us-east-1
- Default output format [None]: json
- aws configure list
Clone the Serverless Framework project:
- cd nestjs-serverless-aws/
The .env environment file must be created with the following variables, these can vary the values:
- IS_OFFLINE=true
- DYNAMODB_ENDPOINT=http://localhost:5000
- USERS_TABLE_NAME=BooksTable
Install global dependencies :
- sudo npm install --save aws-serverless-fastify or sudo npm install
- sudo serverless plugin install -n serverless-plugin-optimize
- sudo serverless plugin install -n serverless-dynamodb-local
- sudo serverless plugin install -n serverless-offline
- sudo serverless dynamodb install
Generate the build and deploy the serverless development project (dev) offline, here we can perform tests locally to verify the project configuration before deploying to the AWS account:
- sudo npm run build && serverless offline start
Generate the build and deploy the serverless project in AWS:
- sudo serverless deploy
should display the endpoints and lambda functions generated from the code for consumption.
Test the operation of the services that allow us to consume endpoints, such as Postman or another tool of your choice, Create .json to be consumed by a POST of the lambda function:
Verify through GET that the information is being stored in DynamoDB by requesting:
In this case, the serverless service is working correctly through the endpoint delivered by the deployment to AWS.
Review of the services used for deployment in the AWS console:
- sudo serverless remove
I hope I have given you a hand if you have doubts write me. successes! ⭐️ From @Diego Márquez