Viewed   88 times

In API 1.0, we can use users/profile_image/:screen_name

For example : http://api.twitter.com/1/users/profile_image/EA_FIFA_FRANCE

But, it doesn't work anymore in API 1.1.

Do you have a solution, please ?

 Answers

5

The user's profile image

Okay, so you want a user's profile image. You're going to need to take a look at the twitter REST API 1.1 docs. This is a list of all the different requests you can make to their API (don't worry, I'll get to how you actually do this later on).

There are multiple ways to get the user's profile image, but the most notable one is: users/show. According to the docs for this, the users/show method:

Returns a variety of information about the user specified by the required user_id or screen_name parameter. The author's most recent Tweet will be returned inline when possible.

Well, the user profile image must be in there somewhere, correct?

Let's have a look at a typical response to a request for this information, using the users/show url (we'll use my profile as an example).

I've cut off some from the bottom, because there is a lot of data to go through. Most importantly, you'll see what you require:

This is the profile_image_url key that you need to get access to.

So, how do you do all this? It's pretty simple, actually.

Authenticated Requests

As you rightly pointed out, as of June 11th 2013 you can't make unauthenticated requests, or any to the 1.0 API any more, because it has been retired. So OAuth is the way to make requests to the 1.1 API.

I wrote a post with an aim to help all you guys make authenticated requests to the 1.1 API with little to no effort.

When you use it, you'll get back the response you see above. Follow the posts instructions, step-by-step, and you can get the library here (you only need to include one file in your project).

Basically, the previous post explains that you need to do the following:

  • Create a twitter developer account
  • Get yourself a set of unique keys from twitter (4 keys in total).
  • Set your application to have read/write access
  • Include TwitterApiExchange.php (the library)
  • Put your keys in a $settings array
  • Choose your URL and request method (Post/Get) from the docs (I put the link above!)
  • Make the request, that's it!

A practical example

I'm going to assume you followed the step-by-step instructions in the above post (containing pretty colour pictures). Here's the code you would use to get what you want.

// Require the library file, obviously
require_once('TwitterAPIExchange.php');

// Set up your settings with the keys you get from the dev site
$settings = array(
    'oauth_access_token' => "YOUR_ACCESS_TOKEN",
    'oauth_access_token_secret' => "YOUR_ACCESS_TOKEN_SECRET",
    'consumer_key' => "YOUR_CONSUMER_KEY",
    'consumer_secret' => "YOUR_CONSUMER_SECRET"
);

// Chooose the url you want from the docs, this is the users/show
$url = 'https://api.twitter.com/1.1/users/show.json';
// The request method, according to the docs, is GET, not POST
$requestMethod = 'GET';

// Set up your get string, we're using my screen name here
$getfield = '?screen_name=j7mbo';

// Create the object
$twitter = new TwitterAPIExchange($settings);

// Make the request and get the response into the $json variable
$json =  $twitter->setGetfield($getfield)
                 ->buildOauth($url, $requestMethod)
                 ->performRequest();

// It's json, so decode it into an array
$result = json_decode($json);

// Access the profile_image_url element in the array
echo $result->profile_image_url;

That's pretty much it! Very simple. There's also users/lookup which effectively does the same thing, but you can:

Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters.

If you ever need to get more than one user's details, use that, but as you only require one user's details, use users/show as above.

I hope that cleared things up a bit!

Monday, November 7, 2022
2

Use the search API and boolean OR operator. For example here is the URL for CNN Breaking News and NPR All Things Considered:

http://search.twitter.com/search.json?q=from%3acnnbrk+OR+from%3anpratc

The query is URLEncoded so use Fiddler Tools -> Text Encode/Decode or your favorite tool to see that the correct format in plain text is:

q=from:cnnbrk+OR+from:npratc

Hope that helps.

Monday, November 28, 2022
1

You can't store the OAuth tokens in cache and to more than 1 request with it, as OAuth is there to help make the system secure, your "oauth_token" will contain some unique data, this token will only be able to make one call back to twitter, as soon as the call was made, that "oauth_token" is no longer valid, and the OAuth class should request a new "oauth_token", thus making sure that every call that was made is secure.

That is why you are getting an "401 unauthorized" error on the second time as the token is no longer valid.

twitter is still using OAuth v1 (v2 is still in the draft process even though facebook and google already implemented it in some parts) The image below describes the flow of the OAuth authentication. Hope it helps.

A while ago I used this to connect to twitter and send tweets, just note that it did make use of some Zend classes as the project was running on a zend server.

require_once 'Zend/Service/Twitter.php';
class Twitter {

    protected $_username = '<your_twitter_username>';
    protected $_token = '<your_twitter_access_token>';
    protected $_secret = '<your_twitter_access_token_secret>';
    protected $_twitter = NULL;

    //class constructor
    public function __construct() {
        $this->getTwitter();
    }

    //singleton twitter object   
    protected function getTwitter() {
        if (null === $this->_twitter) {
            $accessToken = new Zend_Oauth_Token_Access;
            $accessToken->setToken($this->_token)
                    ->setTokenSecret($this->_secret);

            $this->_twitter = new Zend_Service_Twitter(array(
                        'username' => $this->_username,
                        'accessToken' => $accessToken,
                    ));

            $response = $this->_twitter->account->verifyCredentials();
            if ($response->isError()) {
                throw new Zend_Exception('Provided credentials for Twitter log writer are wrong');
            }
        }
        return $this->_twitter;
    }

    //send a status message to twitter
    public function update( $tweet ) {
        $this->getTwitter()->status->update($tweet);
    }

}
Sunday, November 20, 2022
 
1

First, you need to Authenticate your request (Get permission).

second, see follow these steps:

1.Download FHSTwitterEngine Twitter Library.

2.Add the folder FHSTwitterEngine" to your project and #import "FHSTwitterEngine.h".

3.add SystemConfiguration.framework to your project.

Usage : 1.in the [ViewDidLoad] add the following code.

UIButton *logIn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    logIn.frame = CGRectMake(100, 100, 100, 100);
    [logIn setTitle:@"Login" forState:UIControlStateNormal];
    [logIn addTarget:self action:@selector(showLoginWindow:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:logIn];

[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:@"<consumer_key>" andSecret:@"<consumer_secret>"];
    [[FHSTwitterEngine sharedEngine]setDelegate:self];

and don't forget to import the delegate FHSTwitterEngineAccessTokenDelegate.

  1. you need to get the permission for your request, with the following method which will present Login window:
- (void)showLoginWindow:(id)sender {
    [[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self withCompletion:^(BOOL success) {
        NSLog(success?@"L0L success":@"O noes!!! Loggen faylur!!!");
    }];
}

when the Login window is presented, enter your Twitter Username and Password to authenticate your request.

  1. add the following methods to your code:
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[FHSTwitterEngine sharedEngine]loadAccessToken];
    NSString *username = [[FHSTwitterEngine sharedEngine]loggedInUsername];// self.engine.loggedInUsername;
    if (username.length > 0) {
        lbl.text = [NSString stringWithFormat:@"Logged in as %@",username];
        [self listResults];


    } else {
        lbl.text = @"You are not logged in.";
    }

}
- (void)storeAccessToken:(NSString *)accessToken {
    [[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:@"SavedAccessHTTPBody"];
}

- (NSString *)loadAccessToken {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SavedAccessHTTPBody"];
}

4.Now you are ready to get your request, with the following method(in this method I created a Twitter search for some Hashtag, to get the screen_name for example):

- (void)listResults {

    dispatch_async(GCDBackgroundThread, ^{
        @autoreleasepool {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

        // the following line contains a FHSTwitterEngine method wich do the search.

            dict = [[FHSTwitterEngine sharedEngine]searchTweetsWithQuery:@"#iOS" count:100 resultType:FHSTwitterEngineResultTypeRecent unil:nil sinceID:nil maxID:nil];
          // NSLog(@"%@",dict);
            NSArray *results = [dict objectForKey:@"statuses"];

          //  NSLog(@"array text = %@",results);
            for (NSDictionary *item in results) {
                NSLog(@"text == %@",[item objectForKey:@"text"]);
                NSLog(@"name == %@",[[item objectForKey:@"user"]objectForKey:@"name"]);
                NSLog(@"screen name == %@",[[item objectForKey:@"user"]objectForKey:@"screen_name"]);
                NSLog(@"pic == %@",[[item objectForKey:@"user"]objectForKey:@"profile_image_url_https"]);
            }

            dispatch_sync(GCDMainThread, ^{
                @autoreleasepool {
                    UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Complete!" message:@"Your list of followers has been fetched" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [av show];
                    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                }
            });
        }
    });
}

That's all. I just got the screen_name from a search Query, you can get a timeline for a user using the following methods:

// statuses/user_timeline
- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count;
- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count sinceID:(NSString *)sinceID maxID:(NSString *)maxID; 

instead of the search method above.

Note: see the FHSTwitterEngine.h to know what method you need to use. Note: to get the <consumer_key> and the <consumer_secret> you need to to visit this link to register your app in Twitter.

Tuesday, October 11, 2022
 
1

Ferhad, I have spent some time researching this problem and as far as I can ascertain, the links are not available via the Youtube V3 API. However, like you, I'm not convinced that I've explored every option; it's just not clear in the available documentation.

I just did this test: visit the About page of a YouTube channel, e.g. https://www.youtube.com/user/Gap/about, you'll that there is section called "Links" with many URLs. I believe you'll find this on many YouTube channels. I looked at both the YouTube and Google+ APIs (thinking the links might be coming from a linked G+ account), I cannot find a way to retrieve those links via the API.

I tried using "Channels: list" with these parameters:

  • part=auditDetails,brandingSettings,contentDetails,contentOwnerDetails,id,invideoPromotion,snippet,statistics,status,topicDetails
  • id=UCKdDR4GsvrA3yeDhMykoiPQ
  • fields=etag,eventId,items,kind,nextPageToken,pageInfo,prevPageToken,tokenPagination,visitorId

The links were nowhere in the data.

Since there was a linked Google+ account, I tried looking over there, thinking they might be shared between the two platforms. I tried using "People: get" with these parameters:

  • userid=100521075388356747359
  • fields=aboutMe,ageRange,birthday,braggingRights,circledByCount,cover,currentLocation,displayName,domain,emails,etag,gender,id,image,isPlusUser,kind,language,name,nickname,objectType,occupation,organizations,placesLived,plusOneCount,relationshipStatus,skills,tagline,url,urls,verified

The links weren't there. The next area of exploration would be to see if they are only available via OAuth2, but again, it's not evident from the documentation.

Sorry that this is only a partial answer but some times it's hard to prove a negative.

Thursday, August 18, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :