How to query REST API - api

I am using this code below to deal with the REST API query for Adobe Analytics. I always get the message "something went wrong" which means that the first IF is not active.
include_once('/path/SimpleRestClient.php');
$username = 'XXXXX';
$secret = 'XXXXX';
$nonce = md5(uniqid(php_uname('n'), true));
$nonce_ts = date('c');
$digest = base64_encode(sha1($nonce.$nonce_ts.$secret));
$server = "https://api.omniture.com";
$path = "/admin/1.4/rest/";
$rc=new SimpleRestClient();
$rc->setOption(CURLOPT_HTTPHEADER, array("X-WSSE: UsernameToken Username=\"$username\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$nonce_ts\""));
$query="?method=Company.GetTokenUsage";
$rc->getWebRequest($server.$path.$query);
if ($rc->getStatusCode()==200)
{
$response=$rc->getWebResponse();
var_dump($response);
}
else
{
echo "something went wrong\n";
var_dump($rc->getInfo());
}
The $rc->getStatusCode(); does not exit. I get '404' when I use this line :
print_r ($rc->getStatusCode());

After googling, I found https://marketing.adobe.com/developer/blog/how-to-start-with-the-omniture-rest-api-in-php. It uses API version of 1.3 instead of 1.4. By updating the
$path = "/admin/1.4/rest/";
to
$path = "/admin/1.3/rest/";
I was able to stop getting 404 errors in the browser.

Related

Twitter API : /1.1/statuses/retweet/:id returns "Could not authenticate you”,”code”:32

I am using twitter api to get the retweets , for a particular tweets
$url = "https://api.twitter.com/1.1/statuses/retweet/830785820722343937.json";
$requestMethod = 'POST';
$getfield = "";
$twitter = new TwitterAPIExchange($settings);
$string = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$string = json_decode($string,$assoc = TRUE);
But getting this error
[code] => 32
[message] => Could not authenticate you.
Please help
Try after replacing the $url and $requestMethod as follows.
$url = "https://api.twitter.com/1.1/statuses/retweets/830785820722343937.json";
$requestMethod = 'GET';
See https://dev.twitter.com/rest/reference/get/statuses/retweets/id for more.
As I mentioned in comment, the $url and $requestMethod used in your code are not for getting retweets. You are using something else, see https://dev.twitter.com/rest/reference/post/statuses/retweet/id to leaarn about it and find the difference.

Recieving very slow response from twitter usertimeline requests, is the twitter API slow?

I am retrieving tweets from multiple accounts (around 20) and displaying them on a page. The request are very slow and my page takes one to two minutes to load. I am using the twitteroauth library (PHP). If i reduce the number of accounts, the loading time kind of decreases.
Here's the function
//twitter credentials and connection
$consumer_key = variable_get('tw_consumer_key', 'xxxxxxxxxxx'); //consumer key
$consumer_secret = variable_get('tw_consumer_secret', 'xxxxxxx'); // consumer secret
$oauth_token = variable_get('tw_access_token', 'xxxxxxxxxxxx'); //oAuth Token
$oauth_token_secret = variable_get('tw_access_token_secret', 'xxxxxxxxxx'); //oAuth Token Secret
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
$connection->host = "https://api.twitter.com/1.1/";
//Retrieve feeds now
foreach ($twitter_accounts as $account_twitter) {
if (!empty($account_twitter['lien'])) {
$page_url = $account_twitter['lien'];
$twitter_name = $account_twitter['compte'];
$query = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' . $twitter_name . '&exclude_replies=true&include_rts=true&include_entities=true';
$content = $connection->get($query);
if (sizeof($content) > 0 && empty($content->errors)) {
$tw_tweets['posts'] = $content;
$tw_tweets['url'] = $page_url;
$twitter_feeds[] = $tw_tweets;
}//end if sizeof
else {
if (!empty($content->errors)) {
$error = '';
$error = (isset($content->errors[0]->message)) ? $content->errors[0]->message : '';
$error .= (isset($content->errors[0]->code)) ? ' code' . $content->errors[0]->code : '';
watchdog('ffbb_hubsocial', 'Twitter Account ' . $account_twitter['compte'] . ' failed to return results :' . $error);
}
}
}
}
Is the API slow ?
Anyone knows if the problem is with twitter ?
Duplicate question: Why are the Twitter api calls so slow?
As the above answer states, try testing the URL in your browser and see how long it takes. Hence, you'll be able to see if the issue is on your side or due to Twitter.

Yii + Zend gdata. Youtube upload

I want to upload videos with next way:
I just upload file to server (as usual)
My server-side Yii-application takes that video and uploads it on Youtube from a special account on youTube
What do i have:
My YouTube (google) account name and email. "name" or "name#gmail.com"
My password
A developer Key, which I found in Google's "Product Dashboard"
A name of the application, which names 'myapp':
Product Dashboard: myapp
So, I read some docs in google and decided that best way for me is to use ClientLogin auth type, because I have only one account to use and I have all necessary data. I found an example for ZendFramework's GData and I imported it into my Yii application.
I specially simplified the code just to upload one single video from /upload directory to test that it works. I expect to find a video in my YT account uploaded. Of course there is no video and here I am :-) Complete code of the action is below:
Yii::import('application.vendors.*');
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
$yt_user = 'myYTname';
$yt_pass = 'myYTpass';
$yt_source = 'myapp';
$yt_api_key = 'veryVERYlongKEYhere';
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = $yt_user,
$password = $yt_pass,
$service = 'youtube',
$client = null,
$source = $yt_source,
$loginToken = null,
$loginCaptcha = null,
$authenticationURL
);
$yt = new Zend_Gdata_YouTube($httpClient, $yt_source, null, $yt_api_key);
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource(Yii::getpathOfAlias('webroot').'/upload/videos/video.mp4');
$filesource->setContentType('video/mp4');
$filesource->setSlug('video.mp4');
$myVideoEntry->setMediaSource($filesource);
$myVideoEntry->setVideoTitle('My Test Movie');
$myVideoEntry->setVideoDescription('My Test Movie description');
$myVideoEntry->setVideoCategory('Autos');
$myVideoEntry->SetVideoTags('cars, funny');
$myVideoEntry->setVideoDeveloperTags(array('mydevtag', 'anotherdevtag'));
$uploadUrl = "http://uploads.gdata.youtube.com/feeds/api/users/{$yt_user}/uploads";
try {
$newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_HttpException $httpException) {
echo $httpException->getRawResponseBody();
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
As you can see, there is a lot of default code from the official example. But it doesn't work. Noone echo shows me information. But when I deleted try-catch, I got an error:
Zend_Gdata_App_HttpException
Read timed out after 10 seconds
So, this problem is solved by myself :)
First of all: don't try to upload from localhost!
Then in my case I got an error, that I didn't say my dev-key! So, if you got the same error, try to change this:
$newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
by adding the 4th parameter - extra headers:
$yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry', array(
'X-GData-Key' => 'key=yourBIGbigBIGdeveloperKEYhere'
));
Good luck and have fun with youtube API!

Why do I get HTTP 401 Unauthorized from my call the to Yahoo contacts API?

This is driving me crackers. I'm implementing a friend invite scheme on a website and need access to the user's Yahoo contacts list. To do this, I'm using OAuth and the yahoo REST api. Here's a complete rundown of the sequence of events:
I have a project set up on developers.yahoo.com which is configured to have read access to Contacts. It's on a made-up domain which I point to 127.0.0.1 in my hosts file (On the off-chance that localhost was causing my woes). For this reason, the domain is not verified though my understanding is that this simply means I have less restrictions, not more.
Firstly, on the server I get a request token:
https://api.login.yahoo.com/oauth/v2/get_request_token
?oauth_callback=http%3A%2F%2Fdev.mysite.com%2Fcallback.aspx
&oauth_consumer_key=MYCONSUMERKEY--
&oauth_nonce=xmaf8ol87uxwkxij
&oauth_signature=WyWWIsjN1ANeiRpZxa73XBqZ2tQ%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1328796736
&oauth_version=1.0
Which returns with (Formatted for vague attempt at clarity):
oauth_token=hxcsqgj
&oauth_token_secret=18d01302348049830942830942630be6bee5
&oauth_expires_in=3600
&xoauth_request_auth_url
=https%3A%2F%2Fapi.login.yahoo.com%2Foauth%2Fv2%2Frequest_auth
%3Foauth_token%3Dhxcsqgj
&oauth_callback_confirmed=true"
I then pop-up the xoauth_request_auth_url page to the user and receive a verifier code to my callback page. I then send that back to my server so that I can exchange it for an access token:
https://api.login.yahoo.com/oauth/v2/get_token
?oauth_consumer_key=MYCONSUMERKEY--
&oauth_nonce=yxhd1nymwd03x189
&oauth_signature=c%2F6GTcybGJSQi4TOpvueLUO%2Fgrs%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1328796878
&oauth_token=hxcqgjs
&oauth_verifier=b8ngvp <- verifier given via callback
&oauth_version=1.0
That seems to work, and I get an access token back:
oauth_token=MYVERYLONGACCESSTOKEN--
&oauth_token_secret=MYOATHTOKENSECRET
&oauth_expires_in=3600
&oauth_session_handle=ADuXM093mTB4bgJPKby2lWeKvzrabvCrmjuAfrmA6mh5lEZUIin6
&oauth_authorization_expires_in=818686769
&xoauth_yahoo_guid=MYYAHOOGUID
I then immediately attempt to get the contacts list with the access token and the GUID:
http://social.yahooapis.com/v1/user/MYYAHOOGUID/contacts
(HTTP Header added and formatted with line breaks for clarity...)
Authorization: OAuth
realm="yahooapis.com",
oauth_consumer_key="MYCONSUMERKEY--",
oauth_nonce="nzffzj5v82mgf4mx",
oauth_signature="moVJywesuGaPN5YHYKqra4T2ips%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1328796907",
oauth_token="MYVERYLONGACCESSTOKEN--",
oauth_version="1.0"
From this call I get a 401 Unauthorized, but it seems impossible to find out why. To sign these calls, I'm using this oath lib on github. I don't think it's doing anything extraordinary or incompatable. For the signature, I'm including the consumer key/secret and the access token/secret. I've looked at the signature base that's being hashed and it looks to be the same form as the examples visible on yahoo's documentation. I'm guessing that I'm missing something from the parameters that isn't being hashed. Is there a way to find out why the call is unauthorized, or does anyone know of an example showing exactly what form the signature base and authorization header must take?
Solved this myself. Adding the answer just in case it happens to help anyone who makes the same silly mistake I did. When I made the API call, I was using the token secret returned from the original request token call instead of the new one returned from the access token call.
Oops.
this is the code with which I solved, the trusted code to use if yahooapis returns 403 forbidden:
Reference:
https://developer.yahoo.com/yql/guide/yql-code-examples.html#yql_php
https://github.com/danzisi/YQLQueryYahooapis
init CODE
/**
* Call the Yahoo Contact API
*
* https://developer.yahoo.com/yql/guide/yql-code-examples.html#yql_php
*
* #param string $consumer_key obtained when you registered your app
* #param string $consumer_secret obtained when you registered your app
* #param string $guid obtained from getacctok
* #param string $access_token obtained from getacctok
* #param string $access_token_secret obtained from getacctok
* #param bool $usePost use HTTP POST instead of GET
* #param bool $passOAuthInHeader pass the OAuth credentials in HTTP header
* #return response string with token or empty array on error
*/
function call_yql($consumer_key, $consumer_secret, $querynum, $access_token, $access_token_secret, $oauth_session_handle, $usePost=false, $passOAuthInHeader = true){
global $godebug;
$response = array();
if ($consumer_key=='' || $consumer_secret=='' || $querynum=='' || $access_token=='' || $access_token_secret=='' || $oauth_session_handle) return array('0' => 'Forbidden');
if ($querynum == 1) {
$url = 'https://query.yahooapis.com/v1/yql';
// Show my profile
$params['q'] = 'select * from social.profile where guid=me';
} elseif ($querynum == 2) {
$url = 'https://query.yahooapis.com/v1/yql';
// here other query
}
$params['format'] = 'json'; //json xml
$params['Authorization'] = 'OAuth';
$params['oauth_session_handle'] = $oauth_session_handle;
$params['realm'] = 'yahooapis.com';
$params['callback'] = 'cbfunc';
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $consumer_key;
$params['oauth_callback'] = 'oob';
$params['oauth_token'] = $access_token;
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] = oauth_compute_hmac_sig($usePost? 'POST' : 'GET', $url, $params, $consumer_secret, $access_token_secret);
if ($passOAuthInHeader) {
$query_parameter_string = oauth_http_build_query($params, true);
$header = build_oauth_header($params, "yahooapis.com");
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}
// POST or GET the request
if ($usePost) {
$request_url = $url;
logit("call_yql:INFO:request_url:$request_url");
logit("call_yql:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = do_post($request_url, $query_parameter_string, 443, $headers);
} else {
$request_url = $url . ($query_parameter_string ? ('?' . $query_parameter_string) : '' );
logit("call_yql:INFO:request_url:$request_url");
$response = do_get($request_url, 443, $headers);
}
// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
if ($godebug==true) {
echo "<p>Debug: function call_yql info: <pre>" . print_r($info, TRUE) . "</pre></p>";
echo "<p>Debug: function call_yql header: <pre>" . print_r($header, TRUE) . "</pre></p>";
echo "<p>Debug: function call_yql body: <pre>" . print_r($body, TRUE) . "</pre></p>";
}
if ($body) {
$body = GetBetween($body, 'cbfunc(', ')');
$full_array_body = json_decode($body);
logit("call_yql:INFO:response:");
if ($godebug==true) echo "<p>Debug: function call_yql full_array_body: <pre>" . print_r($full_array_body, TRUE) . "</pre></p>";
}
}
// return object
return $full_array_body->query;
}
END code

The sample of FQL query in FB is incorrect. Someone has a correct sample?

The sample posted in the documentation, at:
http://developers.facebook.com/docs/reference/fql/
is incorrect and does not work. (php)
$fql_query_url = 'https://graph.facebook.com/'
. '/fql?q=SELECT+uid2+FROM+friend+WHERE+uid1=me()'
. '&' . $access_token;
$fql_query_result = file_get_contents($fql_query_url);
=> there are two / : ...facebook.com//fql...
=> the word "&access_token" is missing.
However, even issuing the correct url, the function does not seem to return anything...
Here is the code I have been using:
(function is passed $id, like 12345678)
$Fb = new Facebook(array('appId'=>FB_API_ID,'secret'=>FB_API_SECRET));
$access_token = $Fb->getAccessToken();
$fql_query_url = "https://graph.facebook.com/fql?q=SELECT+uid2+FROM+friend+WHERE+uid1=".$id."&access_token=" . $access_token;
$resp = file_get_contents($fql_query_url);
$var = json_decode($resp, true);
$txt .= "<br /><b>FQL QUERY:</b><br />" . display_tree($var);
Someone made it???
This query seems to work for me when I run it in the browser. Are you sure you have a valid access token?
Can you try it from the Graph API Explorer? Here's the link.