Ends in
00
days
00
hrs
00
mins
00
secs
ENROLL NOW

🎁 Get 20% Off - Christmas Big Sale on All Practice Exams, Video Courses, and eBooks!

Building Serverless APIs with AWS API Gateway and AWS Lambda

Last updated on August 11, 2023

Are you looking to create robust and scalable APIs without dealing with infrastructure management? In this article, we’ll look at how to use AWS Lambda and AWS API Gateway to create serverless APIs. You may build APIs that automatically grow, are simple to manage, and offer a seamless user experience by using these services.

Your APIs’ front door is AWS API Gateway, and AWS Lambda handles the backend computation. Using this integration, you can create reliable and adaptable APIs without worrying about managing infrastructure or servers. Let’s examine the relationship between Lambda and API Gateway in more detail.

Two ways of integrating Lambda with API Gateway:

AWS – This type of integration lets an API expose AWS service actions. In AWS integration, you must configure both the integration request and integration response and set up necessary data mappings from the method request to the integration request and from the integration response to the method response.

AWS_PROXY – This type of integration lets an API method be integrated with the Lambda function invocation action with a flexible, versatile, and streamlined integration setup. This integration relies on direct interactions between the client and the integrated Lambda function.

When using the AWS_PROXY integration type, API Gateway passes the incoming request from the client as the input to the backend Lambda function, including request headers, URL path variables, query string parameters, and applicable body.

Step-by-Step Guide

We will create a serverless API using the AWS_PROXY type to generate random jokes for this guide. The response will depend on the input resource path from API Gateway request “/chuck-norris” or “/programming”.

Create and Configure Your Lambda Function

  • For this article, we will use Nodejs. We will first create a Lambda function.

Building Serverless APIs with AWS API Gateway and AWS Lambda

  • Paste the following code to your handler file.

    import axios from 'axios';
    export const handler = async(event) => {
        let result;
        if(event.path === '/chuck-norris'){
            result = await getChuckNorrisJokes();
        }else{
            result = await getProgrammingJokes();
        }
        
         
        const response = {
            statusCode: 200,
            body: JSON.stringify({
                joke: result
            }),
        };
        return response;
    
    };
    
    async function getJokesData(apiUrl){
        try {
        const response = await axios.get(apiUrl);
        return response.data;
      } catch (error) {
        console.error('Error fetching data:', error);
        return null;
      }
    }
    
    async function getChuckNorrisJokes(){
        try {
        const response = await getJokesData("https://api.chucknorris.io/jokes/random");
        return response.value;
      } catch (error) {
        console.error('Error fetching data:', error);
        return null;
      }
    }
    
    async function getProgrammingJokes(){
        try {
        const response = await getJokesData("https://v2.jokeapi.dev/joke/Programming");
        const {joke, setup, delivery, type} = response;
        if(type === "single"){
            return joke;
        }else{
            return `${setup} ${delivery}`;
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        return null;
      }
    }
    
Tutorials dojo strip
 

NOTE: This is just a sample code. Feel free to change it according to your preference.

  • Create a lambda layer – Lambda layers provide a convenient way to package libraries and other dependencies that you can use with your Lambda functions. Using layers reduces the size of uploaded deployment archives and makes it faster to deploy your code.

Building Serverless APIs with AWS API Gateway and AWS Lambda

NOTE: We will need an Axios library to request external APIs that we are gonna use. For Nodejs, make sure to follow this path structure when zipping the library “nodejs/node_modules”.

  • Attach Lambda Layer to Lambda function

Building Serverless APIs with AWS API Gateway and AWS Lambda

Create and Configure REST API in API Gateway

  • Create a REST API

Building Serverless APIs with AWS API Gateway and AWS Lambda

  • Add new Resource

Building Serverless APIs with AWS API Gateway and AWS Lambda

  • Create GET Method

Building Serverless APIs with AWS API Gateway and AWS Lambda

NOTE: Make sure to Tick Use Lambda Proxy Integration. This will configure the API to use the AWS_PROXY integration type.

  • Repeat the same process with /programming resource

API Deployment

  • Deploy the API

Building Serverless APIs with AWS API Gateway and AWS Lambda

Building Serverless APIs with AWS API Gateway and AWS Lambda

NOTE: This deployment will create a URL https://3izcewu3kg.execute-api.us-east-1.amazonaws.com/v1 that you will use to call the API later.

Any further changes in the API Gateway configuration will not be included in the stage deployment. Unless you will redeploy to the same stage again to deploy the changes on the same deployment stage.

Testing the deployed API

You can use several apps to test the deployed API, like Postman, but since we used only the GET Method, we can use the browser for testing the API. Copy the URL and add the /programming or /chuck-norris at the end:

Building Serverless APIs with AWS API Gateway and AWS Lambda

Building Serverless APIs with AWS API Gateway and AWS Lambda

Choosing the Right Integration Type

You should consider the complexity and needs of your REST API when combining Lambda with API Gateway; if you want a more straightforward setup with less modification, the AWS_PROXY integration may be appropriate. However, AWS integration is good if you need fine-grained control and unique logic for each endpoint. Choose the integration option that most closely reflects your REST API design objectives.

Conclusion

You may open up opportunities by creating a REST API using AWS API Gateway and AWS Lambda. In this post, we looked at the general characteristics and advantages of the two integration strategies—AWS_PROXY and Lambda Function integration. Using these services, we also went through the process of creating a REST API. When selecting the integration type, keep in mind the needs of your REST API. You can create scalable, adaptable REST APIs using Lambda and API Gateway that provide top-notch user experiences. So, utilize AWS and serverless APIs to their full potential!

References:

 

Get 20% Off – Christmas Big Sale on All Practice Exams, Video Courses, and eBooks!

Tutorials Dojo portal

Learn AWS with our PlayCloud Hands-On Labs

Tutorials Dojo Exam Study Guide eBooks

tutorials dojo study guide eBook

FREE AWS Exam Readiness Digital Courses

FREE AWS, Azure, GCP Practice Test Samplers

Subscribe to our YouTube Channel

Tutorials Dojo YouTube Channel

Follow Us On Linkedin

Recent Posts

Written by: Bill Junidez Liad

Bill works as a Cloud and DevOps Engineer and is situated in the Philippines. He is actively engaged in furthering his knowledge of the cloud and has significant experience with Web Application Development and Amazon Web Services (AWS). He presently has three AWS Associate certifications. He enjoys biking outside of tech.

AWS, Azure, and GCP Certifications are consistently among the top-paying IT certifications in the world, considering that most companies have now shifted to the cloud. Earn over $150,000 per year with an AWS, Azure, or GCP certification!

Follow us on LinkedIn, YouTube, Facebook, or join our Slack study group. More importantly, answer as many practice exams as you can to help increase your chances of passing your certification exams on your first try!

View Our AWS, Azure, and GCP Exam Reviewers Check out our FREE courses

Our Community

~98%
passing rate
Around 95-98% of our students pass the AWS Certification exams after training with our courses.
200k+
students
Over 200k enrollees choose Tutorials Dojo in preparing for their AWS Certification exams.
~4.8
ratings
Our courses are highly rated by our enrollees from all over the world.

What our students say about us?