Wednesday, May 11, 2016

Being stupid while calling Twitter's Search API

A few days ago, I just figured out how to authenticate my Ionic app using Twitter's application-only Oauth. Application only authentication allows you call Twitter APIs without that Twitter login screen.

The being stupid part started when I tried using the Search API.

    var twitterStreamURL = "https://api.twitter.com/1.1/search/tweets.json?q="; 
    var qValue = "queryString";
    var numberOfTweets = "&count=10";

It should be easy to see that to call the Search API you'll concatinate the qValue (or query string) and the numberOfTweets (number of tweets to get) to the twitterStreamURL. You'd do then a ajax call then get the resulting JSON.
    
    var cURL = "https://api.twitter.com/1.1/search/tweets.json?q=" + qvalue + numberOfTweets; 

These would be no problem with the query string had only one value or no special characters. This stumped me a bit because I used escape() function at first which I knew about. It still works but the escape() function is deprecated. Which lead me to encodeURI(). It worked until it was asked to search for strings with hash tags. I didn't read the fine print for encodeURI which said it doesn't encode certain special characters. This finally lead me to the encodeURIComponent() function.
    
    var cURL = "https://api.twitter.com/1.1/search/tweets.json?q=" + encodeURIComponent(qvalue) + numberOfTweets; 

The moral of this story is I need read the fine print.