Design a site like this with WordPress.com
Get started

[12] [ProjectX] – Deploy Swagger APIs using AWS Serverless Application Model (SAM)

Source code: https://git.io/fjz4t

Credit: https://github.com/jenseickmeyer/todo-app-nodejs

AWS SAM (https://git.io/vb4O9)

This time, we will look at one more method for deploying serverless projects. It is called AWS Serverless Application Model or SAM in short.

AWS SAM is an open-source specification for deployment of serverless projects. It is like a domain specific deployment language created by optimizing cloud formation templates further for serverless projects

Because of this, you end up writing few lines of code of SAM template, which in turn gets converted into a lot more lines of code of cloud formation template.

However, SAM has specific opinions on your code structure should be, so we will be making changes to our code as per SAM specifications

Swagger (https://swagger.io/)

Until now, we were creating our APIs directly. However, the right way to do it is to first Design your APIs and then Implement it. Also, since APIs you create will be most likely consumed by others, it is better to design them in a standardized form. This is where Swagger comes into picture

Swagger is an open-source software framework that helps developers design, build, document, and consume RESTful Web services. It brings the whole ecosystem of standards, tools, specifications, best practices and people to help build best APIs possible.  On 1st January 2016, the Swagger specification was renamed Open API Specification (https://www.openapis.org/). However we will refer to it as swagger.

Here are the steps we will complete in this blog post.

  1. Setup Project structure
  2. Design API with Swagger
  3. Integrate swagger file with Lambda functions
  4. Write code to implement Lambda functions
  5. Define deployment template as per SAM specs
  6. Deploy project using SAM template and CLI commands
  7. Verify all resources are created properly
  8. Testing of API
  9. Clean up

Let’s get started.

1. Project Setup

Create a folder structure as shown below and copy all the files by visiting GitHub page for this blog

Here we have following files.

  1. Swagger.yaml : This file is Design of our API.
  2. Swagger-integrated.yaml : This file connects API designed using Swagger specification to our Lambda functions.
  3. Sam-template.yaml : This file is template defined for deployment using SAM

We need to initialize our project. For this, open terminal in src folder and type following command

npm init

enter below values and press ENTER for rest of values to keep it default

Name: books-catalog-api

Description: package for REST API implementation of books catalog

This completes initialization of our project.

Now, we need to install uuid package. For that, open terminal in books-catalog-api path and execute below script

npm install uuid

Now we need to get latest version of sam cli installed

If you are using Cloud9 IDE, you would already have sam cli installed. But we have to upgrade it to latest version

Execute the following commands to upgrade it. Statements starting with “#” are comments.

# Uninstall the older version of SAM Local

npm uninstall -g aws-sam-local

# Remove the symlink

rm -rf $(which sam)

# Install the CLI

pip install –user aws-sam-cli

# Create new symlink

ln -sf $(which sam) ~/.c9/bin/sam

# Reset the bash cache

hash -r

# Verify your installation worked

sam –version

This completes Step-1.

2. Design API with Swagger

There are many tools available for API design. We will use online Swagger editor available at https://editor.swagger.io/

Usually, API design involves writing them in YAML or JSON format. In this case, we already have the API design available. So, let’s look at it.

Open Swagger online editor and paste contents of swagger.yaml file on left side box.

You should be able to see the API definitions on right side as shown below

From the display on right side, we can see the API methods we have defined for CRUD operations on our books catalog. This can be confirmed by seeing the outline of YAML code on left.

Also, below you can see a schema defined for Book. If you expand it, you can see its details

If we check the first GET function defined to Get all books, it looks like below

This is how APIs are defined as per Swagger/OpenAPI specification

This completes Step-2.

Having finished the design of API, next step is to integrate it in our project with other artifacts.

3. API Integration

To integrate our API with Lambda function, we have to add a code snippet similar to the following to each of the API methods described above during API design.

This basically tells AWS that whenever Get All Books API method is called, it can execute Lambda function called GetAllBooksFunction.

We have modified swagger.yaml file and added such code snippets for all 5 methods. This can be found in swagger-integrated.yaml file.

This completes Step-3.

4. Implement Lambda functions

This code can be found in src folder.

You will find two files. index.js and service.js

If you open index.js, you will see the following structure

This file is our entry point to Lambda and contains implementation code for each API method defined above. The other file (service.js) contains code for communicating with DynamoDB NoSQL database.

This completes Step-4.

5. Creating SAM template

Now we need to write a template file in SAM specification format in order to deploy all the above resources.

You can see below structure of SAM template. It is similar in format to cloud formation template but contains different sections specific to serverless resources deployment. However, you can also define regular cloud formation resources inside this template if you want.

Also, if we were to expand the BooksCatalogApi section, we will see our swagger file defined here (swagger-integrated.yaml). This is how you communicate your API design to AWS

When this template is deployed, the following resources will be created in AWS

  1. An API Gateway for Books catalog with 5 methods
  2. A table in DynamoDb NoSQL database
  3. Five lambda functions corresponding to 5 API methods
  4. Five IAM roles, defining permission for each lambda function

This completes Step-5.

6. SAM Deployment

SAM uses an S3 bucket to copy files before they are deployed to aws. So we need to create a bucket

Execute the following command

aws s3 mb s3://sam-07062019

Now we need to package the artifacts. This is done by executing following command

Note: Below command must be executed at books-catalog-api folder level

Note: in my case, I am using bucket “aws-sam-deployment”. But you should use “sam-07062019”

Packaging creates a deployment template file, which can be seen below (sam-template-output.yaml)

Now let’s proceed to deploy this file. Execute the following command

It will take quite some time but after deployment is done, you should be able to see above message.

This completes last step in our last, i.e. Step-6

7. Verification

Now let’s verify whether all resources have been created properly.

Everything looks OK. So, lets proceed to testing.

8. Testing

Since there is nothing present in our database, let’s start with Adding a couple of books

Test-1: Add Book

URL: https://onserx9cha.execute-api.us-east-1.amazonaws.com/dev/

Method: POST

Body/Payload:

{ “name”: “Game of thrones”, “price”: “15.99”, “author”: “George R R Martin” }

Result:

Add one more book

{ “name”: “Redemption”, “price”: “12.27”, “author”: “David Baldacci” }

We can confirm it by checking in DynamoDB database

Test-2: Get all books

URL: https://onserx9cha.execute-api.us-east-1.amazonaws.com/dev/

Method: GET

Body/Payload: none

Result:

Test-3: Get one books

URL: https://onserx9cha.execute-api.us-east-1.amazonaws.com/dev/be8a2566-4b36-40d9-b2c7-319c0460c007

Method: GET

Body/Payload: none

Result:

Test-4: Update a book

Here let’s change price from 12.99 to 13.95

URL: https://onserx9cha.execute-api.us-east-1.amazonaws.com/dev/be8a2566-4b36-40d9-b2c7-319c0460c007

Method: PUT

Body/Payload:

{ “name”: “Redemption”, “price”: “13.95”, “author”: “David Baldacci” }

Result:


Test-5: Delete a book

URL: https://onserx9cha.execute-api.us-east-1.amazonaws.com/dev/be8a2566-4b36-40d9-b2c7-319c0460c007

Method: DELETE

Body/Payload: none

Result:

9. Clean up

For cleaning up everything, go to AWS CloudFormation and Delete books-catalog-api-stack

Conclusion

As you can see, SAM brings an ease to deployment of serverless application rather than using AWS CLI or AWS CloudFormation. Hence this is the recommended method of deployment by AWS for serverless projects.

Happy Clouding!

Advertisement

2 thoughts on “[12] [ProjectX] – Deploy Swagger APIs using AWS Serverless Application Model (SAM)

  1. […] already familiar with other ways provided by AWS for resource creation like AWS Console, AWS CLI, AWS SAM, AWS CloudFormation etc. Now we have one more option […]

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: