I am using this code to establish a new connection on user device.
var socket = new WebSocket("wss://cdsbxtx2xi.execute-api.us-east-2.amazonaws.com/test");
socket.onmessage = function (event) {
json = JSON.parse(event.data);
connectionId = json.connectionId;
document.cookie = "connection_id="+connectionId;
console.info(json);
}
Suppose from this request I get connectionId CLO5bFP1CYcFSbw=
Another user from another device also established a new connection with connectionId Cs42Fs5s5yuSbc=. Now how can I send a message from user 2 device to user 1?
I already tried this. I don't know this is right way or not but still, i am open for any suggestion.
use Aws\Signature\SignatureV4;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Aws\Credentials\Credentials;
$client = new GuzzleHttp\Client();
$credentials = new Credentials("XXXXXXXXXX","XXXXXXXX");
$url = "https://cdsbxtx2xi.execute-api.us-east-2.amazonaws.com/test/#connections/CLO5bFP1CYcFSbw=";
$region = 'us-east-2';
$msg['action'] = 'sendmessage';
$msg['data'] = 'hello world';
$msg = json_encode($msg);
$request = new Request('POST', $url, '["json"=>$msg]');
$s4 = new SignatureV4("execute-api", $region);
$signedrequest = $s4->signRequest($request, $credentials);
$response = $client->send($signedrequest);
echo $response->getBody();
This code keeps on loading and finally throws gateway timeout error.
I expect that user 2 should be able to send message to any specific connectionId over wss or https.
I tried https by signing this request but signing doesn't works. I am getting an error with the signing part
After struggling with this problem for the last 3 days finally I found the solution. None of the previously mentioned solutions on StackOverflow was working for me.
This is the correct solution. I hope this will be helpful to someone.
use Aws\Signature\SignatureV4;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Aws\Credentials\Credentials;
$client = new GuzzleHttp\Client();
$credentials = new Credentials(accessKeyId, secretAccessKey);
$url = "https://xsdsdsd.execute-api.us-east-2.amazonaws.com/test/#connections/CNtBveH2iYcCKrA=";
// CNtBveH2iYcCKrA= is connectionid
$region = 'us-east-2';
$msg['action'] = 'sendmessage';
$msg['data'] = 'hello world';
$msg = json_encode($msg);
$headers = array('Content-Type => application/x-www-form-urlencoded');
$request = new GuzzleHttp\Psr7\Request('POST', $url, ['Content-Type' => 'application/json'], $msg);
$signer = new Aws\Signature\SignatureV4('execute-api', $region);
$request = $signer->signRequest($request, $credentials);
$headers = array('Content-Type => application/x-www-form-urlencoded');
$client = new \GuzzleHttp\Client([ 'headers' => $headers]);
$response = $client->send($request);
$result = $response->getBody();
Hey you can use the Connection URL to send message also.
Connection url : https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/#connections
To find go to : Aws console > Api gateway > api > your_api > dashboard their you will find your connection url.
Use php cURL method because its easy and fast as compare to GuzzleHttp
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/#connections/{YOUR_CONNECTION_ID_OF_USER}',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{"message" : "Hello world"}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
I am writing code to test the file upload using PHPUnit in Laravel 5.3. I am JWT and I am sending the token in the header (HTTP_Authorization), but the token is not reaching the server. The code is given below.
Please tell me what is wrong with my code?
public function testUpload()
{
$content = $this->post('users/login', ['password' => 'mypass',
'email' => 'scko#gmail.com'])->response->getContent();
$data = json_decode($content);
$token = $data->token;
$stub = 'D:/work/gw.png';
$name = str_random(8).'.png';
$path = 'D:/storage/userfiles/78/'.$name;
copy($stub, $path);
$file = new \Illuminate\Http\UploadedFile($path, $name, filesize($path), 'image/png', null, true);
$response = $this->call('POST', 'files/uploadcardimage', ['HTTP_Authorization' => $token], [] ['file' => $file], ['Accept' => 'application/json']);
$content = json_decode($response->getContent());
echo json_encode($content);
die;
}
I am using Google Tracks API to build a simple web based program to track a vehicle that has a tracking device sending latitude and longitude coordinates.
I am using PHP and the OAuth2 PHP library to make an authorized connection.
After authorizing and getting an access token I am making a request to create entities. Though I can't seem to get this working and keep getting a "400 Bad Request" response. Following all the steps shown in the documentation.
Here is my code:
$url = 'https://www.googleapis.com/tracks/v1/entities/create/?access_token='.$parsedAuth['access_token'];
$data = array('entities' => array( "name"=> "Chevrolet" ));
$json_data = json_encode($data);
$data_length = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n". "Content-Length: " . strlen($data_length) . "\r\n",
'method' => 'POST',
'content' => $json_data
),
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
var_dump($response);
Exact Error is: "failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request"
Why am I getting a bad request? What would be a good request that will register these entities and return id's?
Thank you
The answer given here is wrong. The documentation states that it must be a POST see here My issue was not with the Auth but with the Tracks API itself. I ended up moving to create the request with CURL and it works just fine.
Please. This is PHP with CURL. It works 100%.
//Google maps tracks connection
//Get Files From PHP Library
require_once 'google-api-php-client/src/Google/autoload.php';
require_once 'google-api-php-client/src/Google/Service/MapsEngine.php';
//Set Client Credentials
$client_id = '*************.apps.googleusercontent.com'; //Client ID
$service_account_name = '************#developer.gserviceaccount.com'; //Email Address
$client_email = '*************#developer.gserviceaccount.com';
$private_key = file_get_contents('************.p12');
$scopes = array('https://www.googleapis.com/auth/tracks');
//Create Client
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
//Send Credentials
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($credentials);
}
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$client->setAssertionCredentials($credentials);
$_SESSION['service_token'] = $client->getAccessToken();
foreach ($_SESSION as $key=> $value) {
$vars = json_decode($value);
}
$parsedAuth = (array) $vars;
$token = $parsedAuth['access_token'];
//all functions in the program use this auth token- It should be global for easy accesses.
global $token;
function createEntities(){
global $token;
$url = 'https://www.googleapis.com/tracks/v1/entities/create/?access_token='.$token;
//FIX ME: fields is temporarily hard coded- should be brought from DB
$fields = array(
'entities' => array(
'name' => "DemoTruck",
'type' => "AUTOMOBILE"
),
);
//json string the data for the POST
$query_string = '';
foreach($fields as $key => $array) {
$query_string .= '{"' . urlencode($key).'":[{';
foreach($array as $k => $v) {
$query_string .= '"' . urlencode($k) . '":"' . urlencode($v) . '",';
}
}
$str = rtrim($query_string , ',');
$fstr = $str.'}]}';
$length = strlen( $fstr );
//open connection
$ch = curl_init();
//test connection
if (FALSE === $ch)
throw new Exception('failed to initialize');
//set options
$header = array('Content-type: application/json');
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fstr);
$result = curl_exec($ch);
//dump in case of error
if (FALSE === $result){
var_dump( curl_error($ch) );
var_dump( curl_getinfo($ch) );
}
//close connection
curl_close($ch);
}
I've followed the directions posted in this stackoverflow question, but I am stuck.
I am using tumblr/tumblr.php from Github (the official "PHP client for the tumblr API").
I am also following directions here (which are actually for twitter), but those directions aren't tailored for the git library I am using.
I have a valid consumer key and secret.
From those I make a request and get oauth_token and oauth_token_secret like so:
$client = new Tumblr\API\Client($consumerKey,$consumerSecret);
$client->getRequestHandler()->setBaseUrl('https://www.tumblr.com/');
$req = $client->getRequestHandler()->request('POST', 'oauth/request_token', [
'oauth_callback' => '...',
]);
// Get the result
$result = $req->body->__toString();
print_r( $result );
Which gives me:
oauth_token=2C6f...MqSF&oauth_token_secret=HaGh...IJLi&oauth_callback_confirmed=true
Then I send the user to the http://www.tumblr.com/oauth/authorize?oauth_token=2C6f...MqSF, so they can allow access for the app. This redirects to: ...?oauth_token=2C6f...MqSF&oauth_verifier=nvjl...GtEa#_=_
And now in the final step I believe I am supposed to convert my request token to an access token. Is that right? I am doing something wrong:
$client = new Tumblr\API\Client($consumerKey,$consumerSecret);
$client->getRequestHandler()->setBaseUrl('https://www.tumblr.com/');
$req = $client->getRequestHandler()->request('POST', 'oauth/access_token', [
'oauth_token' => '2C6f...MqSF',
'oauth_verifier' => 'nvjl...GtEa'
]);
// Get the result
$result = $req->body->__toString();
print_r( $result );
because I get responses like this one:
oauth_signature [AqbbYs0XSZ7plqB0V3UQ6O6SCVI=] does not match expected value [0XwhYMWswlRWgcr6WeA7/RrwrhA=]
What is wrong with my last step?
I am not sure if I should even be sending oauth_verifier with the request. Is #_=_ supposed to be part of oauth_verifier? I wouldn't think so. I get signature errors for all the variations Ive tried.
Without the token and tokenSecret I can't make certain calls to the API. I get unauthorized 403 responses. Same when I use the token and token_secret from the second step. I'm pretty sure I need a new token/secret pair.
You're pretty close, you just are passing the oauth_token incorrectly in the last step, and skipping out on oauth_token_secret altogeter.
I've compiled this working code (which you can also now find posted on the Wiki at https://github.com/tumblr/tumblr.php/wiki/Authentication):
<?php
require_once('vendor/autoload.php');
// some variables that will be pretttty useful
$consumerKey = '<your consumer key>';
$consumerSecret = 'your consumer secret>';
$client = new Tumblr\API\Client($consumerKey, $consumerSecret);
$requestHandler = $client->getRequestHandler();
$requestHandler->setBaseUrl('https://www.tumblr.com/');
// start the old gal up
$resp = $requestHandler->request('POST', 'oauth/request_token', array());
// get the oauth_token
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// tell the user where to go
echo 'https://www.tumblr.com/oauth/authorize?oauth_token=' . $data['oauth_token'];
$client->setToken($data['oauth_token'], $data['oauth_token_secret']);
// get the verifier
echo "\noauth_verifier: ";
$handle = fopen('php://stdin', 'r');
$line = fgets($handle);
// exchange the verifier for the keys
$verifier = trim($line);
$resp = $requestHandler->request('POST', 'oauth/access_token', array('oauth_verifier' => $verifier));
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// and print out our new keys
$token = $data['oauth_token'];
$secret = $data['oauth_token_secret'];
echo "\ntoken: " . $token . "\nsecret: " . $secret;
// and prove we're in the money
$client = new Tumblr\API\Client($consumerKey, $consumerSecret, $token, $secret);
$info = $client->getUserInfo();
echo "\ncongrats " . $info->user->name . "!\n";
I am trying to call following Twitter's API to get a list of followers for a user.
http://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=username
And I am getting this error message in response.
{
code = 215;
message = "Bad Authentication data";
}
I can't seem to find the documentation related to this error code. Anyone has any idea about this error?
A very concise code without any other php file include of oauth etc.
Please note to obtain following keys you need to sign up with https://dev.twitter.com and create application.
<?php
$token = 'YOUR_TOKEN';
$token_secret = 'YOUR_TOKEN_SECRET';
$consumer_key = 'CONSUMER_KEY';
$consumer_secret = 'CONSUMER_SECRET';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path
$query = array( // query parameters
'screen_name' => 'twitterapi',
'count' => '5'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_token' => $token,
'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("&","&",$url); //Patch by #Frewuill
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
foreach ($twitter_data as &$value) {
$tweetout .= preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '$1$2$4', $value->text);
$tweetout = preg_replace("/#(\w+)/", "#\\1", $tweetout);
$tweetout = preg_replace("/#(\w+)/", "#\\1", $tweetout);
}
echo $tweetout;
?>
Regards
The only solution I've found so far is:
Create application in twitter developer panel
Authorize user with your application (or your application in user account) and save "oauth_token" and "oauth_token_secret" which Twitter gives you. Use TwitterOAuth library for this, it's pretty easy, see examples coming with library.
Using this tokens you can make authenticated requests on behalf of user. You can do it with the same library.
// Arguments 1 and 2 - your application static tokens, 2 and 3 - user tokens, received from Twitter during authentification
$connection = new TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, $tokens['oauth_token'], $tokens['oauth_token_secret']);
$connection->host = 'https://api.twitter.com/1.1/'; // By default library uses API version 1.
$friendsJson = $connection->get('/friends/ids.json?cursor=-1&user_id=34342323');
This will return you list of user's friends.
FOUND A SOLUTION - using the Abraham TwitterOAuth library. If you are using an older implementation, the following lines should be added after the new TwitterOAuth object is instantiated:
$connection->host = "https://api.twitter.com/1.1/";
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';
The first 2 lines are now documented in Abraham library Readme file, but the 3rd one is not. Also make sure that your oauth_version is still 1.0.
Here is my code for getting all user data from 'users/show' with a newly authenticated user and returning the user full name and user icon with 1.1 - the following code is implemented in the authentication callback file:
session_start();
require ('twitteroauth/twitteroauth.php');
require ('twitteroauth/config.php');
$consumer_key = '****************';
$consumer_secret = '**********************************';
$to = new TwitterOAuth($consumer_key, $consumer_secret);
$tok = $to->getRequestToken('http://exampleredirect.com?twitoa=1');
$token = $tok['oauth_token'];
$secret = $tok['oauth_token_secret'];
//save tokens to session
$_SESSION['ttok'] = $token;
$_SESSION['tsec'] = $secret;
$request_link = $to->getAuthorizeURL($token,TRUE);
header('Location: ' . $request_link);
The following code then is in the redirect after authentication and token request
if($_REQUEST['twitoa']==1){
require ('twitteroauth/twitteroauth.php');
require_once('twitteroauth/config.php');
//Twitter Creds
$consumer_key = '*****************';
$consumer_secret = '************************************';
$oauth_token = $_GET['oauth_token']; //ex Request vals->http://domain.com/twitter_callback.php?oauth_token=MQZFhVRAP6jjsJdTunRYPXoPFzsXXKK0mQS3SxhNXZI&oauth_verifier=A5tYHnAsbxf3DBinZ1dZEj0hPgVdQ6vvjBJYg5UdJI
$ttok = $_SESSION['ttok'];
$tsec = $_SESSION['tsec'];
$to = new TwitterOAuth($consumer_key, $consumer_secret, $ttok, $tsec);
$tok = $to->getAccessToken();
$btok = $tok['oauth_token'];
$bsec = $tok['oauth_token_secret'];
$twit_u_id = $tok['user_id'];
$twit_screen_name = $tok['screen_name'];
//Twitter 1.1 DEBUG
//print_r($tok);
//echo '<br/><br/>';
//print_r($to);
//echo '<br/><br/>';
//echo $btok . '<br/><br/>';
//echo $bsec . '<br/><br/>';
//echo $twit_u_id . '<br/><br/>';
//echo $twit_screen_name . '<br/><br/>';
$twit_screen_name=urlencode($twit_screen_name);
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $btok, $bsec);
$connection->host = "https://api.twitter.com/1.1/";
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';
$ucontent = $connection->get('users/show', array('screen_name' => $twit_screen_name));
//echo 'connection:<br/><br/>';
//print_r($connection);
//echo '<br/><br/>';
//print_r($ucontent);
$t_user_name = $ucontent->name;
$t_user_icon = $ucontent->profile_image_url;
//echo $t_user_name.'<br/><br/>';
//echo $t_user_icon.'<br/><br/>';
}
It took me way too long to figure this one out. Hope this helps someone!!
The answer by Gruik worked for me in the below thread.
{Excerpt | Zend_Service_Twitter - Make API v1.1 ready}
with ZF 1.12.3 the workaround is to pass consumerKey and consumerSecret in oauthOptions option, not directrly in the options.
$options = array(
'username' => /*...*/,
'accessToken' => /*...*/,
'oauthOptions' => array(
'consumerKey' => /*...*/,
'consumerSecret' => /*...*/,
)
);
UPDATE:
Twitter API 1 is now deprecated. Refer to above answer.
Twitter 1.1 does not work with that syntax (when I wrote this answer). Needs to be 1, not 1.1. This will work:
http://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=username
The url with /1.1/ in it is correct, it is the new Twitter API Version 1.1.
But you need an application and authorize your application (and the user) using oAuth.
Read more about this on the Twitter Developers documentation site
:)
You need to send customerKey and customerSecret to Zend_Service_Twitter
$twitter = new Zend_Service_Twitter(array(
'consumerKey' => $this->consumer_key,
'consumerSecret' => $this->consumer_secret,
'username' => $user->screenName,
'accessToken' => unserialize($user->token)
));
After two days of research I finally found that to access s.o. public tweets you just need any application credentials, and not that particular user ones. So if you are developing for a client, you don't have to ask them to do anything.
To use the new Twitter API 1.1 you need two things:
the Abraham's TwitterOAuth library that Dante Cullari already mentioned
a brand new or already working application created via the Twitter Developer site
First, you can (actually have to) create an application with your own credentials and then get the Access token (OAUTH_TOKEN) and Access token secret (OAUTH_TOKEN_SECRET) from the "Your access token" section.
Then you supply them in the constructor for the new TwitterOAuth object. Now you can access anyone public tweets.
$connection = new TwitterOAuth( CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET );
$connection->host = "https://api.twitter.com/1.1/"; // change the default
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';
$tweets = $connection->get('http://api.twitter.com/1.1/statuses/user_timeline.json?screen_name='.$username.'&count='.$count);
Actually I think this is what Pavel has suggested also, but it is not so obvious from his answer.
Hope this saves someone else those two days :)
This might help someone who use Zend_Oauth_Client to work with twitter api. This working config:
$accessToken = new Zend_Oauth_Token_Access();
$accessToken->setToken('accessToken');
$accessToken->setTokenSecret('accessTokenSecret');
$client = $accessToken->getHttpClient(array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0', // it was 1.1 and I got 215 error.
'signatureMethod' => 'HMAC-SHA1',
'consumerKey' => 'foo',
'consumerSecret' => 'bar',
'requestTokenUrl' => 'https://api.twitter.com/oauth/request_token',
'authorizeUrl' => 'https://api.twitter.com/oauth/authorize',
'accessTokenUrl' => 'https://api.twitter.com/oauth/access_token',
'timeout' => 30
));
It look like twitter api 1.0 allows oauth version to be 1.1 and 1.0, where twitter api 1.1 require only oauth version to be 1.0.
P.S We do not use Zend_Service_Twitter as it does not allow send custom params on status update.
Be sure that you have read AND write access for application in twitter
I'm using HybridAuth and was running into this error connecting to Twitter. I tracked it down to (me) sending Twitter an incorrectly cased request type (get/post instead of GET/POST).
This would cause a 215:
$call = '/search/tweets.json';
$call_type = 'get';
$call_args = array(
'q' => 'pancakes',
'count' => 5,
);
$response = $provider_api->api( $call, $call_type, $call_args );
This would not:
$call = '/search/tweets.json';
$call_type = 'GET';
$call_args = array(
'q' => 'pancakes',
'count' => 5,
);
$response = $provider_api->api( $call, $call_type, $call_args );
Side note: In the case of HybridAuth the following also would not (because HA internally provides the correctly-cased value for the request type):
$call = '/search/tweets.json';
$call_args = array(
'q' => 'pancakes',
'count' => 5,
);
$response = $providers['Twitter']->get( $call, $call_args );
I was facing the same problem all the time the only solution I figurae out is typing CONSUMER_KEY and CONSUMER_SECRET directly to new TwitterOAuth class defination .
$connection = new TwitterOAuth( "MY_CK" , "MY_CS" );
Don't use variable or statics on this and see if the issue sloved .
Here first every one need to use oauth2/token api then use followers/list api.
Other wise you will get this error. Because followers/list api requires Authentication.
In swift (for mobile app) me also got the same problem.
If you want to know the api's and it's parameters follow this link , Get twitter friends list in swift?
I know that this is old but yesterday I faced the same issue when calling this URL using C# and the HttpClient class with the Bearer authentication token:
http://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=username
It turns out that the solution for me was to use HTTPS instead of HTTP. So my URL would look like this:
https://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=username
So here is a snippet of my code:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.twitter.com/1.1/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer **** YOUR BEARER TOKEN GOES HERE ****");
var response = client.GetAsync("statuses/user_timeline.json?count=10&screen_name=username").Result;
if (!response.IsSuccessStatusCode)
{
return result;
}
var items = response.Content.ReadAsAsync<IEnumerable<dynamic>>().Result;
foreach (dynamic item in items)
{
//Do the needful
}
}
Try this twitter API explorer, you can sign in as a developer and query whatever you want.