Calling dotnet core Lambda API direct from PHP

Usually a API Gateway is placed in front of a Lambda to allow HTTP requests to be forwarded to a Lambda function. However even when using the HTTP API this still costs $1 per million invocations. To save costs I have setup the PHP website to call the Lambda function direct. Here is how to call the Lambda function and pass the request parameters through in a similar way to how you would call any other JSON API service.

function CallLambdaApiFunctionRequest($path, $method, $queryStringParameters) {
    if (isset($_SESSION['signaccesstoken'])) {
        $queryStringParameters['accesstoken'] = $_SESSION['signaccesstoken'];
    }

    $client = LambdaClient::factory([
        'version' => 'latest',
        'region'  => 'eu-west-1',
        'credentials' => [
            'key'    => '<AWS-ACCESS-KEY>',
            'secret' => '<AWS-SECRET>',
        ]
    ]);

    $bodyContent = null;

    try
    {
        $payload = array ('rawQueryString' => http_build_query($queryStringParameters), 'requestContext' => array('http' => array('method' => $method, 'path' => $path)));
        $result = $client->invoke([
            'FunctionName' => '<LAMBDA-FUNCTION-NAME>',
            'Payload' => json_encode($payload)
        ]);
        $bodyContent = json_decode($result->get('Payload')->getContents())->body;
    }
    catch (LambdaException $e) // Catch an Lambda specific exception.
    {
        error_log($e);
        error_log($e->getAwsErrorCode());
        $_SESSION['lasterrormessage'] = 'Error! ' . $e->getAwsErrorCode() . ' Please try again in a few moments.';
    }

    return json_decode($bodyContent, true);
}

Note: If the Lambda function is not using version 2 i.e. your LambdaEntryFunction.cs file starts with:

public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction

Rather than:

public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction

Then you will need to adjust line 19 to be:

$payload = array ('path' => $path, 'queryStringParameters' => $queryStringParameters, 'httpMethod' => $method);

As the structure of the data expected will be different.

Daniel Mitchell

Daniel Mitchell