RestfulAPI powered by AWS-Lambda

aditya goel
8 min readJan 23, 2022

--

In case you are landing here directly, it’s recommended to read through this documentation first.

In this particular blog, we would demonstrate following aspects :-

  • Full fledged Restful API backed by Lambda behind APIGateway.
  • Creation of resources using CloudFormation “template.yaml”.

Part #1) :- First, let’s define our global properties, which shall be applicable to all the resources we shall be creating below :-

Concept #1.) We have created an environment variable with name as “ORDERS_TABLE” and we use the intrinsic function called reference.

Concept #2.) Purpose of using this Intrinsic-Function is that : This table that gets created dynamically at runtime. We need access to that in our codebase. So, we use this intrinsic function, assign that table reference to this: ORDERS_TABLE.

Part #2) :- Now, create a DynamoDB table using the CloudFormation template :-

Through the above CloudFormation template, we defined a DynamoDB table resource. Under properties section, we have also defined the Primarykey of the database table “id” of type number. CloudFormation will create a database for us. It will create a table inside that database called OrdersTable. Database shall be created on its own.

Part #3) :- Now, let’s write our first code for eCommerce application. We shall be exposing an POST APIs in order to create Orders into the DynamoDB.

CreateOrder → The code for creating the order looks something like this :-

Part #4) :- Next, let’s write template.yaml file for this particular CreateOrder Lambda function :-

Concept #1.) Can you explain the Properties section :-

  • CodeUri → This is that folderName which would contain the template.yaml file.
  • Handler This contains the FQDN for the code-file where our actual Lambda Function is being coded within Java directory.

Concept #2.) Can you explain the “Events” section ?

Answer:- This “Events” section is the one, which shall be trigger-ring our Lambda function.

  • The “OrderEvents” section creates a API gateway endpoint.
  • Type is “Api”, which stands for API-Gateway.
  • Path” defines the endpoint with which this API endpoint should be created and it should be binded to the HTTP method post

Concept #3.) What’s the Implicit Block ?

Answer:- Within “CreateOrdersFunction” section, we have the implicit block called Events. This way of defining the API-Gateway is known as Implicit Block.

Concept #4.) What’s so special about “OrderEvents” section as Implicit Block?

Answer:- This Implicit block not only creates the API gateway end-point, but it also binds that to our lambda above so that, the API gateway will automatically trigger this lambda function “CreateOrderFunction”. All that will be done for us magically.

Concept #5.) What does Policies indicates ?

  • We have created “DynamoDBCrudPolicy”, which is a type of security-policy, to tell that, our Lambda function would be performing CRUD operations on the mentioned table.
  • Note here that, “!Ref” is an intrinsic CFN function, because we are creating the DynamoDB table on the fly i.e. table itself shall be created dynamically using the template.yaml file.
  • This Policy will give our lambda function the permissions to perform CRUD operations against the mentioned Dynamo DB tables. In our case, it’s OrdersTable only.

Concept #6.) From where does DynamoDBCrudPolicy has come ?

Answer:- These policies (e.g. DynamoDBCrudPolicy) are already defined in sam and in cloud formation as the name itself says.

Part #5) :- Now, let’s write our next piece of code GET APIs in order to access all our Orders from the DynamoDB.

ReadOrder → The code for reading all the orders looks something like this :-

Part #6) :- Next, let’s write template.yaml file for this particular ReadOrder Lambda function :-

Concept #1.) Can you explain the “Events” section ?

Answer:- This “Events” section is the one, which shall be trigger-ring our this particular Lambda function i.e. ReadOrdersFunction.

  • The “OrderEvents” section creates a API gateway endpoint.
  • Type is “Api”, which stands for API-Gateway.
  • Path” defines the endpoint with which this API endpoint should be created and it should be binded to the GET method post

Concept #2.) What’s the beauty of “OrderEvents” section as Implicit Block?

Answer:- This Implicit block not only creates the API gateway end-point, but it also binds that to our lambda above so that, the API gateway endpoint, will automatically trigger this lambda function “ReadOrdersFunction”. All that will be done for us magically.

Concept #3.) What does Policies indicates ?

Answer:-

  • We have created “DynamoDBReadPolicy”, which is a type of security-policy, to tell that, our Lambda function can perform only Read operations on the mentioned table. Note here, that “ReadOrdersFunction” lambda function can NOT perform the CRUD operation with this policy.
  • Note here that, “!Ref” is an intrinsic function, because we are creating the DynamoDB table on the fly.
  • This Policy will give our lambda function the permissions to perform READ operations against the mentioned Dynamo DB tables. In our case, it’s OrdersTable only.
  • These policies (e.g. DynamoDBReadPolicy) are already defined in sam and in cloud formation as the name itself says.

Part #7) :- Next, let’s enable more debugging logs during the “sam deploy” command :-

Concept #1.) With above block, we as a developer want to provide some useful information that can be done using the Outputs key. You can create any custom key. We have created here CreateOrdersAPI.

Concept #2.) With the above configuration, we would not need to go every-time to the AWS API Gateway resource on the AWS-Console every time, rather we shall be able to get these URLs in the output of sam deploy command itself. Instead of that, we can generate those on the fly.

Concept #3.) We are going to use the intrinsic-function provided by cloud formation called !Sub. We already use the intrinsic function earlier called. I want to build the API gateway URL that gets generated on the fly and same shall be substituted in mentioned URL.

Part #8) :- Here is our final yaml file looks like :-

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
ordersapi

Sample SAM Template for ordersapi

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 30
Runtime: java8
MemorySize: 512
Environment:
Variables:
ORDERS_TABLE: !Ref OrdersTable

Resources:
OrdersTable:
Type: AWS::Serverless::SimpleTable
Properties:
PrimaryKey:
Name: id
Type: Number

CreateOrdersFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabspw/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: ordersapi
Handler: com.aditya.learn.function.CreateOrderLambda::createOrder
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref OrdersTable
Events:
OrderEvents:
Type: Api
Properties:
Path: /orders
Method: POST

ReadOrdersFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabspw/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: ordersapi
Handler: com.aditya.learn.function.ReadOrderLambda::readOrders
Policies:
- DynamoDBReadPolicy:
TableName: !Ref OrdersTable
Events:
OrderEvents:
Type: Api
Properties:
Path: /orders
Method: GET

Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
CreateOrdersAPI:
Description: "API Gateway endpoint URL for Prod stage for Create Orders API"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/orders/"
CreateOrdersFunction:
Description: "Create Orders Lambda Function ARN"
Value: !GetAtt CreateOrdersFunction.Arn
CreateOrdersFunctionIamRole:
Description: "Create Orders Lambda Function ARN"
Value: !GetAtt CreateOrdersFunctionRole.Arn

Note that, the alignment of each section is very important in the “template.yaml” file, in absence of which the build process further might fail.

Part #9) :- Let’s go ahead and perform our build :-

sam build

Part #10) :- Let’s go ahead and deploy our Lambda :-

sam deploy

Note here that, we are able to get the endpoint of our API (exposed behind the API Gateway) from the logs output of “sam deploy” itself.

Part #11) :- Let’s now hit to the above Restful endpoint and observe whether ORDERS are getting created or not ?

Part #12) :- Let’s now hit to the above Restful endpoint and observe whether ORDERS are getting created or not ?

Part #13) :- Let’s now go ahead and verify the API-Gateway resource from AWS Console and it’s evident that, TWO apis have been well created here :-

Part #14) :- Let’s now go ahead and drill down inside the POST /orders API and we are able to see the 2 environments i.e. PROD and STAGE environments. Also note that, for PROD environment, the endpoint of this API-Gateway has also been exposed here :-

Part #15) :- Let’s now go verify the DynamoDB table that has got created through our CFN template :-

  • Note here, some adhoc chars have been appended with the name of the DynamoDB table and this is the reason, we needed the !Ref function while referring it in our template.yaml file.
  • Also, we can very well observe the entries present in this table.

That’s all in this section. If you liked reading this blog, kindly do press on clap button multiple times, to indicate your appreciation. We would see you in next series.

References :-

--

--