How to Build and Deploy a Serverless API Using AWS CDK

How to Build and Deploy a Serverless API Using AWS CDK

The popularity of AWS Cloud Development Kit (CDK) is rising and for good reason! After all, this open-source framework makes it easy to harness the power of your most preferred programming languages to model your applications.

 

One of the best-loved features that we use in AWS cloud services is creating an API to perform our desired tasks. But, before the introduction of AWS CDK, it was exhausting to maintain/alter the architecture.


CDK proves to be a life saver because it gives you an option to build your infrastructure as code in AWS. As a result, it is very helpful when it comes to modification or maintenance of infrastructure.  

 

Today, in this tutorial, let’s focus on building a serverless REST API using AWS CDK.

 

Given below are the technical specifications for REST API integration with CDK.
Tool used : AWS CDK
Language used : Python
Other tools required :AWS CLI, code editor

Prerequisite:

  • Install and configure AWS CLI on the system, reference can be found here
    - Create a profile in AWS CLI on your system
  • Install AWS CDK, reference can be found here

 

So let's get started!


To first begin the REST API integration with CDK, let's create a new CDKproject.

 

Navigate into the directory where you want the setup to be and then run given below command to do the same.

 

        cdk init app –language python

 

rest-api-integration-cdk initialize-cdk


Here we will be building the architecture using python as our programming language. If you are comfortable with other languages then you can use the same.

 

Since we are using python, we have to activate the virtual environment.

        

        source .venv/bin/activate

 

rest-api-integration-cdk activate-virtual-env

 

After that, we need to install all the necessary packages.

 

        python -m pip install -r requirements.txt

 

        

rest-api-integration-cdk install-python-libraries

We have successfully created a blank CDK project with default stack. Given below is the folder structure of a blank CDK setup.

 

rest-api-integration-cdk default-code

 

 

If you want to verify your setup, you can run

        

cdk ls

 

This will list down all the stacks in the CDK setup. For me it was AwsApiStack.

 

For creating an API, we will be needing 2 AWS services

  1. API gateway
  2. Lambda

 

So let’s talk about AWS CDK API gateway and AWS CDK Lambda.

 

Let's create those resources now

Navigate to your stack file, during the initial setup CDK creates a default stack. For me it was aws_api > aws_api_stack.py. However, it might change for you based on your directory.

 

In this file, first we need to import necessary resources from our CDK, which are aws_lambda and aws_apigateway.

 

Update the file with given below code:

 

import code

import this

from aws_cdk import (

    # Duration,

    Stack,

    aws_lambda as lambda_,

    aws_apigateway as api_gateway

    # aws_sqs as sqs,

)

from constructs import Construct

 

class AwsApiStack(Stack):

 

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:

        super().__init__(scope, construct_id, **kwargs)

 

        lambdafunc = lambda_.Function(

            self,

            id="test-api-lambda",

            runtime=lambda_.Runtime.PYTHON_3_8,

            handler="handler",

            code= lambda_.Code.from_asset("lambda/")

        )

 

        api = api_gateway.LambdaRestApi(

            self,

            id="api-of-tset-api-lambda",

            handler=lambdafunc,

            proxy=False

        )

        api.root.add_method("GET")

 

Basically in the above code, first, we are defining a AWS CDK lambda function and its properties. For instance, here we have specified python 3.8 as our runtime environment, handler property specifies which handler will be used. Also, we need to provide the asset path, basically the folder where our lambda code will be stored.

 

Then we defined a rest. Here, the handler specifies what needs to be triggered when this API is called. For us, we need to call/trigger our lambda function that's why we have specified our lambda function variable.

 

Also, we have specified what method we are going to use ( GET/POST etc).

Since we have mentioned “lambda” as our code asset in the lambda property (code), we will need to create a folder called lambda in the root directory of our application.

 

 

Also, we need to create a file called lambda.py in the lambda folder refer screenshot.

 

rest-api-integration-cdk lambda.py-file

 

 

In the lambda.py file, paste the given below content

 

import json

def handler(event, context):

    return {

                'statusCode': 200,

                'headers': {'Content-Type': 'application/json'},

                'body': json.dumps({'status': 200, 'body': 'success'})

            }

 

 

Here we have just defined a function called handler (as mentioned in the lambda function definition ) which returns this response.


        {"status": 200, "body": "success"}

 

So ideally our aim here is to call our API and get the above data as a response.

 

Now that the coding is done to build our infrastructure as code in AWS, let's deploy our infrastructure on AWS for REST API integration with CDK.

 

First, let's generate the cloud formation template using given below command.

 

        cdk synth

 

rest-api-integration-cdk cdk-synth

 

Then deploy the stack

        cdk deploy <name-of-the-stack>

        Eg : cdk deploy AwsApiStack

 

Upon successful deployment, you will be displayed api url

 

rest-api-integration-cdk stack-deployment

Upon hitting that url ull get the given below response :


        {"status": 200, "body": "success"}

 

And that's basically all there is to it!

 

Your resources will be successfully deployed on AWS through REST API integration with CDK. You can verify the same using the AWS console.

 

Happy Coding!

 

If you need any further clarifications on REST API integration with CDK or are looking to move your business to the cloud seamlessly and successfully, SJ Innovation offers top-notch AWS Cloud Services. We collaborate with a transparent communication flow so that you aren’t left in the dark and your business operations move forward functionally and securely.

 

Get the best AWS Cloud Consulting Services from us.

Akshay Naik | Sr. Software Engineer
Akshay Naik
Sr. Software Engineer
The New Era of Outsourcing: Solving Talent Gaps or Cost-Cutting?

The New Era of Outsourcing: Solving Talent Gaps or Cost-Cutting?

Shahed Islam
Avoid These 7 Common Manual QA Mistakes and Improve Your Testing Process

Avoid These 7 Common Manual QA Mistakes and Improve Your Testing Process

Ali Reza
Manual vs. Automated Testing: Choosing the Right Approach for Your Project

Manual vs. Automated Testing: Choosing the Right Approach for Your Project

Zahin Ahad