slim Guzzle to psr http. for slim PhpRenderer view - slim

$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'http://127.0.0.1/slim_project/getall',
array(
'headers' => array(
'Authorization' => "Bearer fghfghfgh-sdfsdfs-sdfsdf}",
)
)
);
$data = $response->withBody($res->getBody());
return $this->renderer->render($data->getBody(), 'pages/tables.php');
When i run the code. i got this error.
Argument 1 passed to Slim\Views\PhpRenderer::render() must implement interface Psr\Http\Message\ResponseInterface, instance of GuzzleHttp\Psr7\Stream given, called in /var/www/html/slim_project/index.php on line 101 and defined
How Can i convert Guzzle to psr/http\message. That how can i use this.
Thanks in advance.

return $this->renderer->render($response, 'pages/tables.php', json_decode($data->getBody(), true));

Related

How to Retrieve HTTP Status Code with Guzzle?

New to Guzzle/Http.
I have a API rest url login that answer with 401 code if not authorized, or 400 if missing values.
I would get the http status code to check if there is some issues, but cannot have only the code (integer or string).
This is my piece of code, I did use instruction here ( http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions )
namespace controllers;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
$client = new \GuzzleHttp\Client();
$url = $this->getBaseDomain().'/api/v1/login';
try {
$res = $client->request('POST', $url, [
'form_params' => [
'username' => 'abc',
'password' => '123'
]
]);
} catch (ClientException $e) {
//echo Psr7\str($e->getRequest());
echo Psr7\str($e->getResponse());
}
You can use the getStatusCode function.
$response = $client->request('GET', $url);
$statusCode = $response->getStatusCode();
Note: If your URL redirects to some other URL then you need to set false value for allow_redirects property to be able to detect initial status code for parent URL.
// On client creation
$client = new GuzzleHttp\Client([
'allow_redirects' => false
]);
// Using with request function
$client->request('GET', '/url/with/redirect', ['allow_redirects' => false]);
If you want to check status code in catch block, then you need to use $exception->getCode()
More about responses
More about allow_redirects
you can also use this code :
$client = new \GuzzleHttp\Client(['base_uri' 'http://...', 'http_errors' => false]);
hope help you

need to set headers on guzzle request

I need to add the type of headers to the guzzle request below, but cannot figure out how to put it in without getting an error
This is what I want to add :
$command->set('command.headers', array('content-type' => 'application/x-www-form-urlencoded
to this code below:
<?php
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'form_params' => $post_data,
'verify' => false
]);
$body = $response->getBody();
dsm($body);
?>
When I needed use the Guzzle at D8 to make a POST I passed the Content-Type like this:
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => rawData($post_data),
]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
A good idea is use the D8 Dependency Injection to pass the HTTP_CLIENT.

Drupal7 REST: I am not able to perform POST and PUT methods. Error is :Not Acceptable : Node type is required, Code:406?

I'm using drupal7. my drupal_http_request() for get and delete are working fine for authenticated users, but the post and put methods are not working.
The error is :Not Acceptable : Node type is required, and http error code is :406. My code is below:
function ws_form_post_auth() {
$base_url = 'http://localhost/drupalws/api/v1';
$data = array(
'username' => 'student1',
'password' => 'welcome',
);
$data = http_build_query($data, '', '&');
$options = array(
'headers' => array(
'Accept' => 'application/json',
),
'method' => 'POST',
'data' => $data
);
$response = drupal_http_request($base_url . '/user/login', $options);
$data = json_decode($response->data);
// Check if login was successful
if ($response->code == 200) {
$options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
$options['headers']['X-CSRF-Token'] = $data->token;
$data = array(
'title' => 'First forum post',
'type'=> 'forum',
'body'=> array(
'und'=>array(
0=> array(
'value'=>'This is my first forum post via httprequest.'
)
)
)
);
$data = json_encode($data);
$options['data'] = $data;
$options['method'] = 'POST';
$response = drupal_http_request($base_url . '/node', $options);
return $response->status_message;
}
return $response->status_message;
}
I got the solution for my issue,I just missed a Content-Type in Headers.
[....]
if ($response->code == 200) {
$options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
$options['headers']['X-CSRF-Token'] = $data->token;
$options['headers']['Content-Type'] = 'application/json';
[....]

IPP CustomerAgg 401 on getAccountTransactions

The user flow I'm building for my application is that users can click on myAccounts and I'll display the getCustomerAccounts Results. That works perfectly. Then for each account I have a hyperlink called get transactions. That takes the user to a new page that should list out the transactions for that account. For some reason I'm always getting a 401 Code:ApplicationAuthenticationFailed when I call getAccountTransactions even though the previous call of getCustomerAccounts worked fine.
I'm confused as I imagine the authentication that is failing for the 401 is the exact same that works for the earlier call. Here is my code:
function get_transactions($accountID)
{
IntuitAggCatHelpers::GetOAuthTokens( $oauth_token, $oauth_token_secret);
$signatures = array( 'consumer_key' => OAUTH_CONSUMER_KEY,
'shared_secret' => OAUTH_SHARED_SECRET,
'oauth_token' => $oauth_token,
'oauth_secret' => $oauth_token_secret);
$txnStartDate = '2014-06-01'; // YYYY-MM-DD
$url = FINANCIAL_FEED_URL ."v1/accounts/$accountID/transactions?txnStartDate=$txnStartDate";
$action = 'GET';
$oauthObject = new OAuthSimple();
$oauthObject->setAction( $action );
$oauthObject->reset();
$result = $oauthObject->sign(
array
(
'path' => $url,
'parameters'=>
array
(
'oauth_signature_method' => 'HMAC-SHA1',
'Host' => FINANCIAL_FEED_HOST
),
'signatures'=> $signatures
)
);
$options = array();
$curlError = fopen('php://temp', 'rw+');
$options[CURLOPT_STDERR] = $curlError;
$options[CURLOPT_CUSTOMREQUEST] = $action;
$options[CURLOPT_URL] = $result['signed_url'];
$options[CURLOPT_HEADER] = 1;
$options[CURLOPT_VERBOSE] = 1;
$options[CURLOPT_RETURNTRANSFER] = 1;
$options[CURLOPT_SSL_VERIFYPEER] = true;
$options[CURLOPT_HTTPHEADER] = array
(
'Accept:application/json',
'Content-Type:application/json',
//'Content-Length:' . strlen( $postData ),
'Host:'. FINANCIAL_FEED_HOST,
//'Authorization:' . $result['header']
);
$curlError = fopen('php://temp', 'rw+');
$options[CURLOPT_STDERR] = $curlError;
$ch = curl_init();
curl_setopt_array( $ch, $options );
$responseText = urldecode( curl_exec( $ch ) );
echo $responseText;
//display curl http conversation
rewind( $curlError );
stream_get_contents( $curlError );
fclose( $curlError );
$httpCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
curl_close( $ch );
return $responseText;
}
Using same certificate(.p12) please try the above getAccountTransaction call from APIExplorer tool.
https://developer.intuit.com/apiexplorer?apiname=CustomerAccountData
Usage Ref - https://developer.intuit.com/docs/0020_customeraccountdata/007_firstrequest
If that works well, then compare the request header and URL with the same from your above code. 401 suggests authentication error which comes when your OAuth header is not properly formed/incorrect. Above comparison should sort this out.
PN - While uploading .p12 file(SAML) in ApiExplorer, sometiems, I get the following error msg.
"Your certificate is invalid. Please use base64 encoded CER format and make sure that the file is not empty". If you get the same then this can't be tested in ApiExplorer.
Thanks
This worked for me:
$result = $oauthObject->sign(array(
'path' => FINANCIAL_FEED_URL . 'v1/accounts/400037865348',
'parameters'=> array('oauth_signature_method' => 'HMAC-SHA1',
'Host'=> FINANCIAL_FEED_HOST,
'txnStartDate' => '2014-01-01',
'txnEndDate' => '2014-08-29'),
'signatures'=> $signatures));
Found at https://intuitpartnerplatform.lc.intuit.com/questions/797819-how-to-get-txnstartdate-into-my-url-without-breaking-oauth-authentication.

Getting Response Body using Zend_http_Client

I am succesfully calling a REST API with the following code
$client = new Zend_Http_Client();
$client->setMethod(Zend_Http_Client::POST);
$client->setUri('http://www.example.com/api/type/');
$client->setParameterPost(array(
'useremail' => '******#*****.***',
'apikey' => 'secretkey',
'description' => 'TEST WEB API',
'amount' => '5000.00'
));
However I would like to get both the header value-(201) and Response Body that are returned after the execution.
How do I proceed with that?
I am assuming that you're actually executing the request via:
$response = $client->request();
At that point all you need is in the $response object,
//Dump headers
print_r($response->headers);
//Dump body
echo $response->getBody();
Refer to the Zend_Http_Response docs at:
http://framework.zend.com/apidoc/1.10/
for more methods that are available.
this should work...
$client->setUri ( $image_source_urls );
$response = $client->request ( 'GET' );
$folder_content = $response->getBody ();