Storing JSON document in DynamoDB using PHP AWS SDK - php

I read the documentation where there are PHP examples to insert data in a dynamicDB table using AWS SDK. However this is for tabular data. I am trying to insert JSON data i.e. Key Value pair where value is a JSON document. How do I do that ?
I tried the following code from the doc but it does not work unless value is an array.
<?php
require '/home/ubuntu/vendor/autoload.php';
use Aws\DynamoDb\DynamoDbClient;
$client = DynamoDbClient::factory(array(
'profile' => 'default',
'region' => 'ap-southeast-1',
'version' => '2012-08-10'
));
$id = "key";
$value = '{"subKey":"value"}'
$result = $client->putItem(array(
'TableName' => 'myTable',
'Item' => array(
'key' => $value
)
));
It gave me following error
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Found 2 errors while validating the input provided for the PutItem operation: [Item][key] must be an associative array. Found string(1) "2" [Item][userId] must be an associative array. Found string(18) "{"subKey":"value"}"' in /home/ubuntu/vendor/aws/aws-sdk-php/src/Api/Validator.php:38 Stack trace: #0 /home/ubuntu/vendor/aws/aws-sdk-php/src/Middleware.php(78): Aws\Api\Validator->validate('PutItem', Object(Aws\Api\StructureShape), Array) #1 /home/ubuntu/vendor/aws/aws-sdk-php/src/AwsClient.php(208): Aws\Middleware::Aws\{closure}(Object(Aws\Command)) #2 /home/ubuntu/vendor/aws/aws-sdk-php/src/AwsClient.php(202): Aws\AwsClient->executeAsync(Object(Aws\Command)) #3 /home/ubuntu/vendor/aws/aws-sdk-php/src/AwsClient.php(167): Aws\AwsClient->execute(Object(Aws\Command)) #4 /var/www/html/dynamoDB.php(25): Aws\AwsClient->__call('putItem', Array) #5 /var/www/html/dynamoDB.php(25): Aws\DynamoDb\DynamoDbClient->putItem(Array) #6 {main} thrown in /home/ubuntu/vendor/aws/aws-sdk-php/src/Api/Validator.php on line 38

DynamoDB requires you specify the AttributeValue types with the request. Here is the example from https://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-dynamodb.html:
$result = $client->putItem(array(
'TableName' => 'errors',
'Item' => array(
'id' => array('N' => '1201'),
'time' => array('N' => $time),
'error' => array('S' => 'Executive overflow'),
'message' => array('S' => 'no vacant areas')
)
));
For your example try adding DynamoDB types:
$result = $client->putItem(array(
'TableName' => 'myTable',
'Item' => array(
'key' => array('S' => $value)
)
));
Where 'S' could be replaced with 'N', 'B', 'SS', 'NS', 'BS', 'M', 'L', or 'BOOL' as defined here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.DataTypes

Related

Ride reminder api 404 error

When we are calling Uber Products API, its working perfect but when we call Ride Reminder API, we getting following 404 errors:
PHP Fatal error: Uncaught exception GuzzleHttp\Exception\ClientException
with message
Client error: POST https://sandbox-api.uber.com/v1.2/reminders
resulted in a 404 Not Found response:
404 page not found in
/var/www/html/uber/uber/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113
Stack trace:
#0 /var/www/html/uber/uber/vendor/guzzlehttp/guzzle/src/Middleware.php(65):
GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request),
Object(GuzzleHttp\Psr7\Response))
#1 /var/www/html/uber/uber/vendor/guzzlehttp/promises/src/Promise.php(203):
GuzzleHttp\Middleware::GuzzleHttp{closure}(Object(GuzzleHttp\Psr7\Response))
#2 /var/www/html/uber/uber/vendor/guzzlehttp/promises/src/Promise.php(156):
GuzzleHttp\Promise\Promise::callHandler(1,
Object(GuzzleHttp\Psr7\Response), Array)
#3 /var/www/html/uber/uber/vendor/guzzlehttp/promises/src/TaskQueue.php(47):
GuzzleHttp\Promise\Promise::GuzzleHttp\Promise{closure}()
#4 /var/www/html/uber/uber/vendor/guzzlehttp/promises/src/Promise.php(246):
Guzzle in
/var/www/html/uber/uber/vendor/stevenmaguire/uber-php/src/Client.php
on line 173
We are using following sample code to work out, let me know what could be issue.
<?php
include "vendor/autoload.php";
$client = new Stevenmaguire\Uber\Client(array(
'access_token' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'server_token' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'use_sandbox' => true, // optional, default false
'version' => 'v1.2', // optional, default 'v1.2'
'locale' => 'en_US', // optional, default 'en_US'
));
$products = $client->getProducts(array(
'latitude' => '41.85582993',
'longitude' => '-87.62730337'
));
var_dump($products);
$attributes = array(
'reminder_time' => '1429294463',
'phone_number' => '555-555-5555',
'event' => array(
'time' => '1515750429',
'name' => 'John with friends',
'location' => 'Dolores Park',
'latitude' => '37.759773',
'longitude' => '-122.427063',
'product_id' => "737d4e43-9e12-4a81-add3-acb101bab4c7",
),
);
$reminder = $client->createReminder($attributes);
var_dump($reminder);
Please help us to fix this.
Documentation is removed for ride reminders from http://developer.uber.com and they are not currently supported.

Paginating List Cognito Identities in AWS PHP SDK v3

How do I fetch all records when the result is paginated, using the AWS PHP SDK v3? I have the following code:
require_once 'vendor/autoload.php';
$cognitoIdentityClient = new Aws\CognitoIdentity\CognitoIdentityClient([
'region' => 'eu-west-1',
'version' => '2014-06-30',
'credentials' => [
'key' => '**************',
'secret' => '***************',
],
]);
$identities = $cognitoIdentityClient->getPaginator('ListIdentities', [
'IdentityPoolId' => 'eu-west-1:****************************',
]);
which looks like it should work, but produces the error:
Fatal error: Uncaught UnexpectedValueException: There is no ListIdentities paginator defined for the cognito-identity service. in /path/to/vendor/aws/aws-sdk-php/src/Api/Service.php:363
Stack trace:
#0 /path/to/vendor/aws/aws-sdk-php/src/AwsClientTrait.php(23): Aws\Api\Service->getPaginatorConfig('ListIdentities')
#1 /path/to/report.php(24): Aws\AwsClient->getIterator('ListIdentities', Array)
#2 {main}
thrown in /path/to/vendor/aws/aws-sdk-php/src/Api/Service.php on line 363
The getPaginator method exists, but the file data/cognito-identity/2014-06-30/paginators-1.json.php is blank, so no paginators are implemented. I see NextToken in the response, but don't understand the pattern to seamlessly load more results (do (...) {} while (...)?)
I solved it like this:
$identities = [];
$i = $cognitoIdentityClient->listIdentities([
'IdentityPoolId' => IDENTITYPOOLID,
'MaxResults' => 60,
]);
$identities = array_merge($identities, $i->get('Identities'));
while ($nextToken = $i->get('NextToken')) {
$i = $cognitoIdentityClient->listIdentities([
'IdentityPoolId' => IDENTITYPOOLID,
'MaxResults' => 60,
'NextToken' => $nextToken,
]);
$identities = array_merge($identities, $i->get('Identities'));
}

Issue when requesting create segments API v3 through PHP wrapper

I have test-driving for Mailchimp API v3 using your PHP wrapper. It's working great for me But when I'm creating a request using POST for "Create Segment" getting an error (attach screenshot):
Request Code is (through associative array) -
$api_key = "xxxxxxxxxxxxxxxx-us11";
$list_id = "1xx2xx3xx4xx";
$MailChimp = new MailChimp($api_key);
$result = $MailChimp->post('lists/' . $list_id . '/segments', array('name' => 'Testing Data',
'options' => array('match' => 'all',
'conditions' => array('field' => 'type', 'op' => 'is', 'value' => 'Testing'))
));
This request call returning following error -
array (size=2) 'field' => string 'options.conditions' (length=18)
'message' => string 'Schema describes array, object found instead'
(length=44)
I will also tried to create Request (through associative array) -
Method 1:
$api_key = "xxxxxxxxxxxxxxxx-us11";
$list_id = "1xx2xx3xx4xx";
$MailChimp = new MailChimp($api_key);
$result = $MailChimp->post('lists/' . $list_id . '/segments', array('name' => 'Testing Data',
'options' => array('match' => 'all',
'conditions' => array(array('field' => 'type', 'op' => 'is', 'value' => 'Testing')))
));
Method 2:
$api_key = "xxxxxxxxxxxxxxxx-us11";
$list_id = "1xx2xx3xx4xx";
$MailChimp = new MailChimp($api_key);
$result = $MailChimp->post('lists/' . $list_id . '/segments', array('name' => 'Testing Data 4',
'options' => array('match' => 'all',
'conditions' => array(array('field' => 'type'), array('op' => 'is'), array('value' => 'Testing')))
));
Both method will create segment on mailchimp account but not have any conditions. See screenshot -
How to override this problem?
You are missing the condition_type param. It should be selected from the list provided by MailChimp in the endpoint documentation.
For example, IF the field "type" from your MailChimp list is a text field you should use 'condition_type': 'TextMerge'. In this case, conditions should have the following format:
[
{
'condition_type': 'TextMerge',
'field': 'type',
'op': 'is',
'value': 'Testing'
}
]
However, MailChimp MAY have a bug in this endpoint, since TextMerge works only on the EMAIL field. I have also stumbled upon this problem recently:
Mailchimp api v3 - can't create segment based on a TEXT merge field
https://github.com/drewm/mailchimp-api/issues/160

How to update item using expression syntax for dynamodb on a table with both hash and range

I believe this should work, but it doesn't:
$response = $client->updateItem(array(
'TableName' => 'ximoIsThisYou',
'KeyConditionExpression' => 'rep_num = :v_hash and record_created = :v_range',
'ExpressionAttributeValues' => array (
':v_hash' => array('S' => $rep_num),
':v_range' => array('N' => $record_created),
':val1' => array('S' => '447747')
),
'UpdateExpression' => 'set vimeo_id = :val1',
'ReturnValues' => 'ALL_NEW'
));
I get this error:
Uncaught Aws\DynamoDb\Exception\ValidationException:
AWS Error Code: ValidationException, Status Code: 400,
AWS Request ID: UOPKLQER1MI3ANF48PU92IAC3VVV4KQNSO5AEMVJF66Q9ASUAAJG,
AWS Error Type: client,
AWS Error Message: 1 validation error detected: Value null at 'key' failed to satisfy constraint: Member must not be null,
User-Agent: aws-sdk-php2/2.8.2 Guzzle/3.9.3 curl/7.35.0 PHP/5.5.9-1ubuntu4.11
This however does work:
$response = $client->query(array(
'TableName' => 'ximoIsThisYou',
'KeyConditionExpression' => 'rep_num = :v_hash and record_created = :v_range',
'ExpressionAttributeValues' => array (
':v_hash' => array('S' => $rep_num),
':v_range' => array('N' => $record_created)
),
));
KeyConditionExpression is a parameter used for Query.
The condition that specifies the key value(s) for items to be retrieved by the Query action.
You are trying to call UpdateItem, which requires Key. You are getting the validation error because you have not set the required request parameter Key.

Consume ASP.NET WebService In php and return soap error

i am trying to calling .net webservice in php
below is my code.
<?php
$client = new SoapClient("http://test.etech.net/PanelIntegration/PanelIntegration.asmx?wsdl");
<?php
$sh_param = array(
'Username' => 'IntegratorLPI',
'Password' => 'password531');
$headers = new SoapHeader('http://wms.etech.net/', 'UserCredentials', $sh_param);
$client->__setSoapHeaders($headers);
$params = array('CustomerName' => 'Mr Smith','ContactMobileNo' => '01237 376347',
'AddressLine1' => '33 Amblecote Road',
'AddressTown' => 'Cambridgeshire',
'AddressPostCode' => 'NW23 6TR',
'VendorAddressLine1' => '80 Norton Road',
'VendorAddressTown' => 'Hickley ',
'VendorAddressCounty' => 'Cambridgeshire',
'VendorAddressPostCode' => 'NW23 2AQ',
'RegionalOfficeID' => '3',
'ExternalNotes' => 'Case Accepted',
'UPRN' => '',
'InstructionTypeID' => '2',
'PropertyTypeID' => '11',
'PropertyTenure' => '2',
'SurveyorID' => '23',
'RRN' => '0240-9002-0391-3520-0020',
'NewInstruction'=> 'true',
'StatusID' => '1'
);
$result = $client->__soapCall("UpdateInstruction", $params );
print_r( $result);
?>
i have got this error
Fatal error: Uncaught SoapFault exception: [soap:Server] Server was unable to process request. ---> Object reference not set to an instance of an object. in C:\xampp\htdocs\test2.php:33 Stack trace: #0 C:\xampp\htdocs\test2.php(33): SoapClient->__soapCall('UpdateInstructi...', Array) #1 {main} thrown in C:\xampp\htdocs\test2.php on line 33
You probably need to send something like:
$result = $client->__soapCall("UpdateInstruction", array('Instruction' => $params );
Where Instruction is the name of the object that you are passing.
It looks like a NullReferenceException was thrown on the server side. So, it's a matter of the parameters to whatever function is occurring on the server side generating that error.
Regardless of why, per best practices, this is an error in the .NET service. The NullReferenceException should really be replaced with something more specific.
Can you get in touch with whomever wrote the service to get more information to troubleshoot? It's quite possible that you have a parameter misnamed in your $params array, but you're probably going to need some help from the service writer.

Categories