AWS Learning: Simple API using API Gateway and Lambda with CloudFormation (Part 1)

Alex
5 min readApr 8, 2022

Let’s say you would like to build an API without having to maintain the whole infrastructure that comes with it, without provisioning or managing servers, you would like to focus only on how the API looks like and what it should do. In order to do that, you can use two AWS services: API Gateway and AWS Lambda.

In my example below we will have an API that allows you to do operations on books (create/retrieve/update books). For starters this API allows you to do two operations:
- Get all books
- Create a book

The AWS Service that allows you to easily create APIs is the API Gateway. This service allows you to create your API structure, define your methods, add authorization in case you need it, but also offers things such as version management, CORS support and monitoring.

After we have our API structure defined, we need to write the actual implementation. As we have said before, in this case we would like it to be a serverless solution where we will write a small piece of code that would simply run without us having to provision instances or to manage servers. For that we will use two AWS Lambda functions:
- RetrieveBooks: this will be connected to the GET /books endpoint from the API Gateway and it will return a list of all books
- CreateBooks: this will be connected to the POST /books endpoint from the API Gateway and it will receive a JSON that will represent a book.

For the sake of the example we will not connect this to a database, we will only simulate a HTTP 201 from the POST and an HTTP 200 from the GET with a mocked JSON containing the books.

We will create all the above setup using AWS CloudFormation, the AWS service that allows you to provision AWS infrastructure as code.

Prerequisites to try this locally:
- An AWS account
- AWS CLI installation: more details here
- AWS CLI configuration: more details here

The above diagram can be described as CloudFormation as in cloudformation.yaml from this GitHub repository: https://github.com/aribeth007/simple-books-api/tree/main/part1

Below we will take some sections from the CloudFormation and offer some explanations. Then having our AWS account, AWS CLI installed and configured, we can execute a CLI command that will deploy our CloudFormation stack to AWS.

Parameters

The first section of the CloudFormation file consists of the following (code in the github repository above):

  • AWSTemplateFormatVersion: capabilities of the Cloudformation template (more details here)
  • Description: information about what the Cloudformation contains
  • Parameters: used for customising our template (more details here)

Resources

Contains the actual resources that the CloudFormation will create in AWS. In our case the API Gateway, the two Lambda functions, necessary permissions for the API Gateway to invoke the Lambdas or the Lambdas to write logs into Cloudwatch.

  • Lambdas: CreateBooks and RetrieveBooks (code in the above GitHub repository)

For this example I’ve chosen a simple NodeJS lambda function and I have written the code inline (Code section). However we might want to change that in the future by adding the actual code in an S3 bucket. For the sake of simplicity this is inline. AWS Lambda offers the inline code capability only for NodeJS and Python Lambda functions.

Notice the response structure, this is prepared for our API Gateway that we will define below, it will be translated under the hood into a HTTP status 200 and a JSON response body.

At this point another variable worth mentioning is the MemorySize. We have used this to specify how much memory we want to allocate to our lambda function. AWS allows us to specify the MemorySize and increasing the MemorySize parameter will also increase the CPU (you don’t have a specific parameter to set the CPU yourself).

You might notice that the lambda functions have a parameter named Role. This is defined a bit below in the CloudFormation file and it allows our lambda to write logs to Cloudwatch.

  • Api Gateway

We have used an APIGateway v1 (in the next parts we might try it with v2). For this we needed to create a RestAPI, a Deployment for our API, a Resource /books, two Methods (GET books and POST /books) and two LambdaPermission elements for allowing our ApiGateway to connect to our lambdas.

I will not copy/paste the code here but please have a look over these => lines of code.

An interesting part might be this:

Integration:        
IntegrationHttpMethod: POST
Type: AWS_PROXY

AWS_PROXY integration means that the integration type between the API Gateway and the lambda is special, the lambda knows with this type of integration to receive all the parts of the API request, including headers, path parameters, query parameters, the request body etc. Also the lambda returns the format, as we have seen above into a special object. This will be translated on the API side into a HTTP status code and response body.

{             
body: JSON.stringify([
{ id: 1, name: 'Monolith to Microservices', author: 'Sam Newman' },
{ id: 2, name: 'Design It!', author: 'Michael Keeling' },
{ id: 3, name: 'Programming Kotlin', author: 'Venkat Subramaniam'}
]),
statusCode: 200
}

So we have the CloudFormation template containing the API, the two AWS Lambda functions, we have the AWS CLI installation and configuration. The only thing remaining is to deploy our stack in AWS.

We can do that using the following command (see deploy-cloudformation.sh):

aws cloudformation deploy --template-file cloudformation.yaml --stack-name simple-books-api --capabilities CAPABILITY_NAMED_IAM

Now, when checking CloudFormation service in AWS we should see our stack.

Checking ApiGateway service in AWS we should see our API and we should be able to test it (by pressing the Test button).

Until now we have created a simple Books API using CloudFormation.

Follow and subscribe for Part 2 where we will improve our setup.

More AWS stories: click here

--

--