coderain blog

How to Make HTTP POST Requests in AWS Lambda (Node.js): Step-by-Step Guide to Get Cities by Country

AWS Lambda is a serverless computing service that lets you run code without provisioning or managing servers. One common use case for Lambda is integrating with external APIs to fetch or send data. In this guide, we’ll walk through creating a Lambda function in Node.js that makes HTTP POST requests to an external API, retrieves a list of cities based on a country input, and returns the results.

Whether you’re building a travel app, a location-based service, or need to fetch dynamic data from third-party services, this tutorial will equip you with the skills to handle HTTP POST requests in Lambda. We’ll use Node.js for the function logic, axios for simplifying HTTP requests, and a mock API to simulate a backend that returns city data.

2026-01

Table of Contents#

  1. Prerequisites
  2. Step 1: Set Up Your Development Environment
  3. Step 2: Create a Mock API for Testing
  4. Step 3: Initialize Your Node.js Project
  5. Step 4: Write the Lambda Function Code
  6. Step 5: Package and Deploy to AWS Lambda
  7. Step 6: Configure an API Gateway Trigger
  8. Step 7: Test the Lambda Function
  9. Troubleshooting Common Issues
  10. Conclusion
  11. 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#

  1. Go to Beeceptor.com and create a new endpoint (e.g., city-api.free.beeceptor.com).
  2. 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"]
      }
  3. 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:

  1. Accepts a POST request with a country parameter.
  2. Sends a POST request to your mock API.
  3. 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 with JSON.parse().
  • Input Validation: Checks if country is provided to avoid invalid API calls.
  • Axios POST Request: Uses axios.post() to send the country to 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:

  1. In your project directory, select index.js and node_modules.
  2. 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#

  1. Go to the AWS Lambda Console.

  2. Click Create function.

  3. Under "Basic information":

    • Function name: GetCitiesByCountry
    • Runtime: Node.js 18.x (or latest LTS version)
    • Click Create function.
  4. Under "Function code", click Upload from > .zip file.

  5. Select your lambda-post-request.zip file 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#

  1. In your Lambda function dashboard, go to the Configuration tab > Triggers > Add trigger.

  2. 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.
  3. 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#

  1. In the API Gateway console (linked from the trigger), go to Resources > Select your POST method (e.g., /GetCitiesByCountry).
  2. Click Actions > Deploy API.
  3. Deployment stage: New stage (e.g., prod).
  4. 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#

  1. Open Postman and create a new POST request.
  2. Enter your API Gateway URL.
  3. Go to the Body tab > Select "raw" > "JSON".
  4. Enter:
    { "country": "Germany" }
  5. 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 a 400 Bad Request error.
  • Invalid JSON: Send { country: France } (no quotes). Expect a 500 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).

References#