Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access API from AWS API Gateway with PHP SDK 3

Can anyone help figure out how to use AWS Signature, AWS Credentials and PHP SDK 3 to access an API Gateway API? It seems like AWS Signature does not actually attach headers to a Guzzle request.

Here is my code:

<?php

require 'vendor/autoload.php';

use Aws\Credentials\Credentials;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Aws\Signature\SignatureV4;

$access_key = '<access_key>';
$secret_key = '<secret_key>';
$url = 'https://<api-id>.execute-api.us-east-1.amazonaws.com/v1/camel?q=*';
$region = 'us-east-1';

$credentials = new Credentials($access_key, $secret_key);
var_dump($credentials);

$client = new Client();
$request = new Request('GET', $url);
var_dump($request);

$s4 = new SignatureV4("execute-api", $region);
$s4 = new SignatureV4("execute-api", "us-east-1");
$s4->signRequest($request, $credentials);
var_dump($s4);
var_dump($request);

$response = $client->send($request);

And the error I'm getting is:

( ! ) Fatal error: Uncaught exception 
'GuzzleHttp\Exception\ClientException' with message ' in 
/path/to/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on 
line 113

( ! ) GuzzleHttp\Exception\ClientException: Client error: `GET 
https://<api-id>.execute-api.us-east-1.amazonaws.com/v1/camel?q=*` 
resulted in a `403 Forbidden` response: {"message":"Missing 
Authentication Token"} in 
/path/to/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on 
line 113
Call Stack
#   Time    Memory  Function    Location
1   0.0002  234048  {main}( )   ../access.php:0
2   0.2801  486272  GuzzleHttp\Client->send( )  ../access.php:29
3   0.3787  574224  GuzzleHttp\Promise\Promise->wait( ) ../Client.php:106

Line 29 of access.php is:

$response = $client->send($request);

It doesn't appear from the var_dumps that any headers are being added. I am able to successfully test this endpoint in the API Gateway and in Postman. Enabling CORS does not appear to make a difference.

Has anyone solved this issue yet?

This issue is also covered at https://forums.aws.amazon.com/post!reply.jspa?messageID=795522 and https://forums.aws.amazon.com/thread.jspa?messageID=774631&tstart=0 but there are no solutions there.

like image 712
pzzd Avatar asked Mar 05 '26 23:03

pzzd


1 Answers

Thanks, Michael, for your help above.

You have to use the return from new SignatureV4, which is a modified request.

$s4 = new SignatureV4("execute-api", $region);
$signedrequest = $s4->signRequest($request, $credentials);

$response = $client->send($signedrequest);

echo $response->getBody();
like image 64
pzzd Avatar answered Mar 08 '26 12:03

pzzd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!