Take the 2-minute tour ×

For some reasons this part where I fetch JSON data from following url will only works sometimes. And sometimes it will return 404 error, and complain about missing header attribute. It will work 100% of the time if I paste it onto a web browser. So I'm sure the link is not broken or something.

I get the following error in Python:

AttributeError: 'HTTPError' object has no attribute 'header'

What's the reason for this and can it be fixed? Btw I removed API key since it is private.

    url = "http://api.themoviedb.org/3/search/person?api_key=API-KEY&query=natalie+portman"
    req = urllib2.Request(url, None, header)
    f = urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print e.code
    print e.msg
    print e.header
    print e.fp.read()
share|improve this question
@starcom I think you mean "sporadically" not "randomly". I doubt there is a RNG somewhere that determines if your code fails or not, even if it feels like it. –  Hooked Mar 27 '12 at 14:51
@Hooked yes that's a better word to describe it. Sorry English is not my first language ;( –  starcorn Mar 27 '12 at 16:33
add comment

1 Answer

up vote 6 down vote accepted

As is documented here, you need to explicitly accept JSON. Just add the second line after the first.

req = urllib2.Request(url, None, header)
req.add_header('Accept', 'application/json')
share|improve this answer
add comment

Your Answer


