I've been playing with Twitter's REST API to collect stats for work. Data like: follower counts, what Tweets are being faved, etc… There are libraries for working with the API but no good examples for using it directly. So, I wrote my own1. It's not super complicated, but there are some tricky parts. I'm posting my code here for posterity's sake.
Each example follows the same basic flow outlined in Twitter's Application-only Authentication approach.
- Combine the Consumer Key and Consumer Secret (generated when you create an app) to make a Bearer Token.
- Base64 encode the Bearer Token (making sure newlines aren't introduced).
- Use the Bearer Token to obtain an Access Token.
- Use the Access Token to make the actual API call (in this case the basic info for my Twitter account).
- Print a dump of the JSON data that's returned.
Step 5 being where real work would actually happen. It's also where looping for to make additional API requests would take place since the Access Token only needs to be pulled once2.
Here's the code:
A few things to keep in mind with these examples:
- Authentication credentials should not be hard coded in source files.
- They are very high level. Just one step beyond pseudo-code.
- The code is straight procedural and almost certainly not how you should actually do it.
- There is no error handling in these examples.
- There is no accounting for throttling based on the API rate-limits.
- No step to transform strings into RFC 1738 (which the docs say to do) was added since there is no change at this point.
- Probably some other caveats that I'm forgetting.
- Authentication credentials should not be hard coded in source files (in case you missed it the first time).
Generally, I'm all for using code libraries to make life easier. Working with APIs is a different story. Unless whoever makes the API is also providing the library, I'd rather use the service directly. Avoiding third-party dependencies is well worth the little extra work it takes. And, if there are good examples available there's not a huge difference between the levels of effort.
The person I'm helping with this is interested in using the pandas data analysis library which is written in Python. I wrote the first version in that language. I decided to port it to Ruby since that's my go-to language these days. Once I started down the path of multiple versions it was easy to thrown in Perl (my previous language of choice). This was the first time in years that I've written any Perl. It's also the first time I've ever done anything beyond "Hello, World" in Python. All said, it was a good language exercise. It's fun to see the difference between them.
The Access Token only needs to be pulled once for as long as it's valid. It should stay that way unless a specific request to invalidate it occurs.