Erik Thiart
Erik Thiart

Reputation: 391

How to use AWS PHP SDK to access a API gateway endpoint

I need to POST data to an AWS API Gateway URL.

I have no clue how to do this with PHP. (Like I cannot imagine it to be this difficult.)

Any help would be appreciated.

I need to send a JSON body to an API Gateway API (IAM) the SDK does not seem to have any documentation that can help me.

I need to POST this:

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

To an API gateway endpoint using sig 4 Example endpoint (https://myendpoint.com/api)

Upvotes: 2

Views: 1229

Answers (2)

b0tting
b0tting

Reputation: 637

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.

Upvotes: 3

Kubwimana Adrien
Kubwimana Adrien

Reputation: 2531

You can install AWS php sdk via composer composer require aws/aws-sdk-php and here is the github https://github.com/aws/aws-sdk-php . In case you want to do something simple or they don't have what you are looking for you can use curl in php to post data.

$ch = curl_init();

$data = http_build_query([
    "entity" => "Business",
    "action" => "read",
    "limit" => 100
]);

curl_setopt_array($ch, [
    CURLOPT_URL => "https://myendpoint.com/api",
    CURLOPT_FOLLOWLOCATION => true
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data
]);

$response = curl_exec($ch);
$error = curl_error($ch);

Upvotes: 0

Related Questions