Table of Contents#
- Prerequisites
- Step 1: Set Up Your Development Environment
- Step 2: Create a Mock API for Testing
- Step 3: Initialize Your Node.js Project
- Step 4: Write the Lambda Function Code
- Step 5: Package and Deploy to AWS Lambda
- Step 6: Configure an API Gateway Trigger
- Step 7: Test the Lambda Function
- Troubleshooting Common Issues
- Conclusion
- References
Prerequisites#
Before starting, ensure you have the following:
- An AWS account (free tier works).
- Node.js (v14+) and npm installed locally.
- A code editor (e.g., VS Code).
- Basic knowledge of JavaScript and HTTP requests.
- (Optional) AWS CLI for deployment (we’ll cover manual deployment via the AWS Console too).
Step 1: Set Up Your Development Environment#
First, set up your local environment to write and test the Lambda function:
1.1 Install Node.js and npm#
If you haven’t already, download and install Node.js from nodejs.org. npm (Node Package Manager) is included with Node.js. Verify installation by running:
node -v # Should return v14.x or higher
npm -v # Should return 6.x or higher 1.2 Choose a Code Editor#
Use a code editor like VS Code for writing your Lambda function. It includes built-in support for JavaScript and Node.js.
Step 2: Create a Mock API for Testing#
To simulate an external API that returns cities for a given country, we’ll use a mock API endpoint. This lets you follow along without needing a real backend. We’ll use Beeceptor (a free tool to create mock APIs) for this.
2.1 Set Up a Mock API with Beeceptor#
- Go to Beeceptor.com and create a new endpoint (e.g.,
city-api.free.beeceptor.com). - In the Beeceptor dashboard, configure a POST route (e.g.,
/get-cities) with a custom response:- Request Body: Expect a JSON payload like
{ "country": "France" }. - Response: Return a JSON object with cities, e.g.:
{ "country": "France", "cities": ["Paris", "Lyon", "Marseille", "Toulouse"] }
- Request Body: Expect a JSON payload like
- Save the mock endpoint. Note the full URL (e.g.,
https://city-api.free.beeceptor.com/get-cities)—we’ll use this in our Lambda function.
Step 3: Initialize Your Node.js Project#
Next, create a local project to write your Lambda function and install dependencies.
3.1 Create a Project Directory#
Open your terminal and run:
mkdir lambda-post-request && cd lambda-post-request 3.2 Initialize npm#
Initialize a package.json file to manage dependencies:
npm init -y 3.3 Install Dependencies#
We’ll use axios (a popular HTTP client) to simplify making POST requests. Install it via npm:
npm install axios This creates a node_modules folder with axios and its dependencies.
Step 4: Write the Lambda Function Code#
Create a Lambda handler function that:
- Accepts a POST request with a
countryparameter. - Sends a POST request to your mock API.
- Returns the list of cities from the API response.
4.1 Create the Lambda Handler File#
Create a file named index.js in your project directory. This will be your Lambda function’s entry point.
4.2 Write the Code#
Add the following code to index.js:
const axios = require('axios');
// Lambda handler function
exports.handler = async (event) => {
try {
// Step 1: Parse the incoming request body
// API Gateway sends the body as a JSON string; parse it to an object
const requestBody = JSON.parse(event.body);
const country = requestBody.country;
// Step 2: Validate input (ensure country is provided)
if (!country) {
return {
statusCode: 400, // Bad Request
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ error: "Missing required parameter: 'country'" })
};
}
// Step 3: Send POST request to mock API
const mockApiUrl = "https://city-api.free.beeceptor.com/get-cities"; // Replace with your Beeceptor URL
const apiResponse = await axios.post(mockApiUrl, { country: country });
// Step 4: Return the API response to the client
return {
statusCode: 200, // Success
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*" // Enable CORS (adjust for production)
},
body: JSON.stringify(apiResponse.data) // Return cities from mock API
};
} catch (error) {
// Handle errors (e.g., API failure, invalid JSON)
console.error("Lambda Error:", error); // Log to CloudWatch
return {
statusCode: 500, // Internal Server Error
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ error: "Failed to fetch cities. Check logs for details." })
};
}
};Key Code Explanations:#
event.body: Contains the raw request body from API Gateway (as a string). We parse it withJSON.parse().- Input Validation: Checks if
countryis provided to avoid invalid API calls. - Axios POST Request: Uses
axios.post()to send thecountryto your mock API. - Error Handling: Catches errors (e.g., network issues, invalid JSON) and returns a user-friendly message.
- CORS Header:
Access-Control-Allow-Origin: "*"enables cross-origin requests (for testing; restrict in production).
Step 5: Package and Deploy to AWS Lambda#
Now, package your code and deploy it to AWS Lambda.
5.1 Package the Code#
Lambda requires your function and dependencies to be zipped. Zip the index.js file and node_modules folder:
- In your project directory, select
index.jsandnode_modules. - Zip them into a file named
lambda-post-request.zip(ensure the zip root contains these files, not a parent folder).
5.2 Deploy via AWS Console#
-
Go to the AWS Lambda Console.
-
Click Create function.
-
Under "Basic information":
- Function name:
GetCitiesByCountry - Runtime: Node.js 18.x (or latest LTS version)
- Click Create function.
- Function name:
-
Under "Function code", click Upload from > .zip file.
-
Select your
lambda-post-request.zipfile and click Save.
Step 6: Configure an API Gateway Trigger#
To invoke your Lambda function via HTTP, add an API Gateway trigger:
6.1 Create an API Gateway Trigger#
-
In your Lambda function dashboard, go to the Configuration tab > Triggers > Add trigger.
-
Under "Trigger configuration":
- Trigger type: API Gateway
- API: Create a new API
- API type: REST API
- Security: Open (for testing; use API keys or IAM in production)
- Click Add.
-
After creation, expand the trigger details to find your API endpoint URL (e.g.,
https://abc123.execute-api.us-east-1.amazonaws.com/default/GetCitiesByCountry).
6.2 Deploy the API#
- In the API Gateway console (linked from the trigger), go to Resources > Select your POST method (e.g.,
/GetCitiesByCountry). - Click Actions > Deploy API.
- Deployment stage: New stage (e.g.,
prod). - Click Deploy. Your API is now live!
Step 7: Test the Lambda Function#
Test your Lambda function using tools like curl, Postman, or a frontend app.
7.1 Test with curl#
Run this command in your terminal (replace YOUR_API_URL with your API Gateway URL):
curl -X POST -H "Content-Type: application/json" -d '{"country": "France"}' "YOUR_API_URL" Expected Response:
{
"country": "France",
"cities": ["Paris", "Lyon", "Marseille", "Toulouse"]
}7.2 Test with Postman#
- Open Postman and create a new POST request.
- Enter your API Gateway URL.
- Go to the Body tab > Select "raw" > "JSON".
- Enter:
{ "country": "Germany" } - Click Send. You’ll see the mock API’s response with German cities.
7.3 Test Edge Cases#
- Missing
country: Send{}as the body. Expect a400 Bad Requesterror. - Invalid JSON: Send
{ country: France }(no quotes). Expect a500 Internal Server Error(check CloudWatch logs for details).
Troubleshooting Common Issues#
Issue 1: "Cannot find module 'axios'"#
Cause: node_modules was not included in the zip file.
Fix: Re-zip index.js and node_modules (ensure they’re in the root of the zip).
Issue 2: "502 Bad Gateway" from API Gateway#
Cause: Lambda returned an invalid response (e.g., missing statusCode or body).
Fix: Ensure your Lambda function returns an object with statusCode, headers, and body (as in index.js).
Issue 3: CORS Errors in Browsers#
Cause: Missing CORS headers in the Lambda response.
Fix: Add Access-Control-Allow-Origin: "*" to the headers object (restrict to specific domains in production).
Issue 4: Lambda Timeout#
Cause: The external API takes too long to respond.
Fix: Increase Lambda’s timeout (Configuration > General configuration > Timeout) to 10 seconds (max for free tier).
Conclusion#
In this guide, you learned how to create an AWS Lambda function in Node.js that makes HTTP POST requests to an external API. You set up a mock API, wrote a Lambda handler with input validation, deployed with API Gateway, and tested the workflow.
This pattern can be extended to integrate with real-world APIs (e.g., payment gateways, weather services) or databases. For production, add:
- Environment variables (store API URLs securely in Lambda).
- IAM roles (restrict Lambda permissions).
- Error logging (use CloudWatch Logs for debugging).