Select your cookie preferences

We use cookies and similar tools to enhance your experience, provide our services, deliver relevant advertising, and make improvements. Approved third parties also use these tools to help us deliver advertising and provide certain site features.

Testing Lambda with external APIs

This project shows a technique for testing an AWS Lambda using a mock AWS API Gateway, where there is an external API dependency.


Files:

Application Code

import { APIGatewayProxyEvent } from 'aws-lambda';
import axios from 'axios';

export const lambdaHandler = async (event: APIGatewayProxyEvent) => {
    // Getting the weather api from environment variable
    const weatherApi = process.env.WEATHER_API;

    const city = event.pathParameters.city;

    try {
        const { status: statusCode, data: weatherResponse } = await axios.get(`${weatherApi}/${city}`);

        return {
            statusCode,
            body: JSON.stringify(weatherResponse),
        };
    } catch (err: unknown) {
        console.error(err);
        return {
            statusCode: 500,
            body: JSON.stringify({
                message: err instanceof Error ? err.message : 'Oh no! Something went wrong!',
            }),
        };
    }
};

                                                  


GitHub icon Visit the GitHub repo for this pattern.

Clone locally

git clone https://github.com/aws-samples/serverless-patterns/ cd typescript-test-samples/apigw-lambda-external

Authors

Mark White Principal Engineer at Dunelm
Mark White

Presented by Mark White

Principal Engineer at Dunelm

Follow on LinkedIn