Fetch tweets with Twitter API v1.1
2 minutes read
There's a better version of this library called Fetchwitter
If you follow me on Twitter you may have seen me ranting about bugs in the Twitter API v1.1 docs.
The worse documentation of #twitterapi 1.1 suggests make use of @anywhere that actually deprecated on March 5th! https://t.co/WZ9aRfqlRD
— Jabran Rafique (@jabranr) July 8, 2013
With version 1.1, Twitter made OAuth mandatory for every request to its API. Data that used to be public now sat behind a complicated authorisation flow, and most developers weren't happy about it.
I put it off for a few months before accepting I'd have to deal with it eventually. The threads on the Twitter developer forums and Stack Overflow didn't help, so I went to the official docs, and those did.
The API has two authentication models: user authentication and application-only authentication. With user authentication the user authorises your app before it can call the API. With application-only authentication the app makes requests on its own behalf, with some limits on what it can do.
Either way, you exchange your credentials for an access token and use that to call the v1.1 endpoints. Here's the flow.
Step 1: Create an application
Sign in at https://dev.twitter.com/apps and create a new application. Fill in the required fields and Twitter generates your credentials. You only need the consumer key and consumer secret.
Step 2: Exchange credentials for an access token
Make a POST request to the API's OAuth endpoint to swap those credentials for an access token. This request needs Authorization headers, and the response contains an app level bearer access token. Save or cache it so you don't request a new one every time.
Step 3: Request the feed
With the access token you can call the API endpoints and get data back. These requests need Authorization headers too.
Tweets come back as plain text, so links, hashtags and mentions aren't linked. A regex match and replace fixes that, and the example has one as the text2html()text2tweet() function. The full source is on GitHub.