Search code examples
amazon-web-servicesaws-lambdaaws-api-gateway

Trigger a lambda function after a rest api is accessed


I have a rest API in aws api gateway that access's an external http endpoint and returns some data.

Every time this rest api is accessed and returns data, i need to trigger a lambda function that uses the data returned by the rest api. How can i achieve that ?

Tried looking for answers on this and all of them point to how to trigger a lambda function using a rest api.


Solution

  • You can do this in 2 ways.

    1. When a request is sent to api gateway, invoke a lambda, inside this lambda access your external http endpoint and whatever the result comes, invoke another lambda.

    something like this.

    const invoke = async (funcName, payload) => {
      const client = createClientForDefaultRegion(LambdaClient);
      const command = new InvokeCommand({
        FunctionName: funcName,
        Payload: JSON.stringify(payload),
        LogType: LogType.Tail,
      });
    
      const { Payload, LogResult } = await client.send(command);
      const result = Buffer.from(Payload).toString();
      const logs = Buffer.from(LogResult, "base64").toString();
      return { logs, result };
    };
    
    1. Use stepfunctions with api gateway ( which would be similar to 1st operation)