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.
-
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; } }
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.
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
Create and Configure REST API in API Gateway
-
Create a REST API
-
Add new Resource
-
Create GET Method
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
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:
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:
Choose an API Gateway API integration type – Amazon API Gateway
Set up Lambda proxy integrations in API Gateway – Amazon API Gateway
Creating and sharing Lambda layers – AWS Lambda