0

I am learning how to access the Twitter API, but get the error "urllib2.HTTPError: HTTP Error 400: Bad Request" when I run the simple code below:

import urllib2
import simplejson

url = "https://api.twitter.com/1.1/search/tweets.json?screen_name=twitterapi"

if __name__ == "__main__":
    req = urllib2.Request(url)
    opener = urllib2.build_opener()
    f = opener.open(req)
    json = simplejson.load(f)

    for item in json:
        print item.get("created_at")  # this will get the section that is "Created At from JSON"
        print item.get('text')        # this will get the text (in Twitter, a Tweet)

I am unsure why - I have Googled around and can't seem to find why this is returning the Bad Request error. Thanks for any help!

user3718365
  • 515
  • 3
  • 6
  • 13
  • 1
    using requests I get `"Bad Authentication data"` which is also what I see when I use the link. I presume you need an api key. – Padraic Cunningham Jul 14 '14 at 23:07
  • I thought the same, but can't seem to find documentation on a required API key - looking around [here](https://dev.twitter.com/docs/using-search) it doesn't mention an API key. I found [this](http://stackoverflow.com/questions/12544018/twitter-v1-1-400-bad-request) SO thread, and looking at Surpriya K's response, maybe you do? Or is that if you're doing something else (oAuth and tweepy? I'm not sure what a consumer and access token/key are). – user3718365 Jul 14 '14 at 23:13
  • https://apps.twitter.com/app/new this is where you create an application and get api key etc.. I don't use the api but I am sure it is necessary to have a key. – Padraic Cunningham Jul 14 '14 at 23:15
  • @PadraicCunningham, thanks. I created a new application and have an API key and will hunt around for how to use it. – user3718365 Jul 14 '14 at 23:26
  • There is info on how to use the different methods here https://dev.twitter.com/docs/auth – Padraic Cunningham Jul 14 '14 at 23:29

1 Answers1

0

You need an API key, from the docs:

"Please note that now API v1.1 requires that the request must be authenticated, check Authentication & Authorization "

Quick test using curl:

$curl https://api.twitter.com/1.1/search/tweets.json?q=%40twitterapi
{"errors":[{"message":"Bad Authentication data","code":215}]}

So, first, you should get an API Key. Here's some aditional help:

Community
  • 1
  • 1
Esparta Palma
  • 735
  • 5
  • 10
  • Thanks - I created an API key...but where do I go from here? I am sure the answer is in that doucmentation, but again, I'm new, and can't figure where to put this information. – user3718365 Jul 14 '14 at 23:30
  • To consume this or any other API you should send commands. In python you can make it with urllib2 or using any third-party library as requests: https://gist.github.com/kennethreitz/973705 or perhaps a specialized twitter library: https://dev.twitter.com/docs/twitter-libraries – Esparta Palma Jul 14 '14 at 23:40