首页 > 解决方案 > 如何使用 AWS PHP SDK 访问 API 网关终端节点

问题描述

我需要将数据发布到 AWS API Gateway URL。

我不知道如何用 PHP 做到这一点。(就像我无法想象这会如此困难。)

任何帮助,将不胜感激。

我需要将 JSON 正文发送到 API Gateway API (IAM),SDK 似乎没有任何可以帮助我的文档。

我需要发布这个:

{
    "entity": "Business",
    "action": "read",
    "limit": 100
}

使用 sig 4 示例端点 ( https://myendpoint.com/api)到 API 网关端点

标签: phpaws-sdkaws-api-gateway

解决方案


I really struggled with this and finally managed to clear it with the following approach:

require './aws/aws-autoloader.php';

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

$url = '<your URL>';
$region = '<your region>';
$json = json_encode(["Yourpayload"=>"Please"]);

$provider = CredentialProvider::defaultProvider();
$credentials = $provider()->wait();
# $credentials = new Credentials($access_key, $secret_key); # if you do not run from ec2
$client = new Client();
$request = new Request('POST', $url, [], $json);
$s4 = new SignatureV4("execute-api", $region);
$signedrequest = $s4->signRequest($request, $credentials);
$response = $client->send($signedrequest);
echo($response->getBody());

This example assumes you are running from an EC2 or something that has an instance profile that is allowed to access this API gateway component and the AWS PHP SDK in the ./aws directory.


推荐阅读