Rate limiting in the Twitter v1.1 API

Twitter’s new v1.1 API imposes limits on the number of requests that users can make. The limits are detailed at https://dev.twitter.com/docs/rate-limiting/1.1/limits. OSX apps need to be aware of these limits and ensure that users cannot make more requests than they are allocated. Twitter states

“We ask that you honor the rate limit. If you or your application abuses the rate limits we will blacklist it. If you are blacklisted you will be unable to get a response from the Twitter API”

Before making a twitter request I check that the rate limit has not been exceeded. I do this using a requestTwitterStatus method as follows:

-(void) requestTwitterStatus{
NSURL *statusURL = [NSURL URLWithString:@"https://api.twitter.com/1.1/application/rate_limit_status.json?resources=help,users,search,statuses"];
statusRequest = [NSMutableURLRequest requestWithURL:statusURL];
[statusRequest addValue:[NSString stringWithFormat:@"Bearer %@",bearerToken] forHTTPHeaderField:@"Authorization"];
[statusRequest setHTTPMethod:@"GET"];
statusConnection = [[NSURLConnection alloc] initWithRequest:statusRequest delegate:self startImmediately:YES];
}

Here the app’s bearer token is the Authorization token obtained from twitter (see my previous post for details of how to obtain this). The connectionDidFinishLoading method detects when the request has finished. The data obtained is then parsed within connectionDidFinishLoading with the following code (receivedData is the data that the getTweetsConnection has provided and is collected in the connection:(NSURLConnection *)connection didReceiveData:(NSData *)data method);

if (connection == statusConnection) {
NSString *twitterStatus = [[NSString alloc] initWithBytes:[statusData bytes] length:[statusData length] encoding:NSUTF8StringEncoding];
NSDictionary *statusResults = [twitterStatus JSONValue];
NSDictionary *statusDict = [statusResults valueForKey:@"resources"];
NSDictionary *searchStatusDict = [statusDict valueForKey:@"search"];
NSDictionary *searchDict = [searchStatusDict valueForKey:@"/search/tweets"];
requestsRemaining = [[searchDict valueForKey:@"remaining"] intValue];
NSLog(@"requestsRemaining = %d\n", requestsRemaining);
if (requestsRemaining > 0) {
// go ahead and make a request to twitter
} else{
NSLog(@"You have reached twitter's request limit. Please wait 15 minutes before requesting again");
}
return;
}
Advertisements
1 comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: