Due to my experience with the Twitter API through my implementation of ThinkTwit, I’ve had a few questions lately on how to implement the Twitter (Search) API in Python so rather than answer people individually I figured it would be best to share with everyone on my blog.
First of all it’s worth noting that there are a few different API’s that Twitter offers for use to access their service, however they are all quite similar and are all access via the same authentication method: OAuth. Before you can access anything via Twitter (since the update from v1 to v1.1 in June 2013) you would need to sign up for a Twitter Developer account so you can create an Application to generate credentials that you must use to authenticate.
Once you have set up your Application you must then create your code to undertake the authentication; you can do this yourself (as I did in ThinkTwit) or you can use a library. For this article I presume you are going to be using Python but other libraries exist in different languages so you can just Google them and pick whatever suits you. Finally, once you have achieved all of this you can use the search/tweets or direct_messages API, or try another API that is on offer.
Here are the steps you should follow:
- Setup an Application account: https://dev.twitter.com/apps/new, take note of the application name, consumer key and consumer secret for steps 4 and 3
- Download and implement an OAuth library e.g. http://oauth.net/code/
- Utilise the OAuth library to authenticate yourself and obtain a token using the generated consumer key and consumer secret for step 4
- Make a call using the Twitter API: e.g. https://dev.twitter.com/docs/api/1.1/get/search/tweets (Search) or https://dev.twitter.com/docs/api/1/post/direct_messages/new (Direct Message)Don’t forget to supply the token in the header request such as (though you may not need this if using a library):
POST /oauth2/token HTTP/1.1
Host: api.twitter.com
User-Agent: {APP_NAME}
Authorization: Bearer {TOKEN}
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
I’ve not yet got any experience with Python to provide any code but I think this should be enough to get most people going; if anyone has any further questions let me know, and if necessary I’ll have a quick look through the Python manual and throw together a working example.