Using the Twitter API without 3rd Party Libraries

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 own^1^^. 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.

1. Combine the Consumer Key and Consumer Secret (generated when you create an app to make a Bearer Token. 2. Base64 encode the Bearer Token (making sure newlines aren't introduced). 3. Use the Bearer Token to obtain an Access Token. 4. Use the Access Token to make the actual API call (in this case the basic info for my Twitter account). 5. 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 once^2^^.

Here's the code:

### Ruby

### Python

### Perl

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.


1. The person I'm helping with this is interested in using the pandas data analysis library. 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.

2. 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.