python - Unable to access Tastekid’s API. It says Error: 403 (Request forbidden) -


i unable run code read tastekid's api (python), says error: 403 (request forbidden) can access same url in browser. have tried same key aswell.

please find below query

from urllib2 import request, urlopen, urlerror req = request('http://www.tastekid.com/api/similar?q=red+hot+chili+peppers%2c+pulp+fiction') try:     response = urlopen(req) except urlerror e:     if hasattr(e, 'reason'):         print 'we failed reach server.'         print 'reason: ', e.reason     elif hasattr(e, 'code'):         print 'the server couldn\'t fulfill request.'         print 'error code: ', e.code else:     'everything fine' 

you need add proper headers before making request url

headers = { 'user-agent' : "mozilla/4.0 (compatible; msie 5.5; windows nt)" }     req = request('http://www.tastekid.com/api/similar?q=red+hot+chili+peppers%2c+pulp+fiction', headers = headers) 

here user-agent key within headers set tell server making request browser rather program

test

  • file name test.py

    from urllib2 import request, urlopen, urlerror  #changes made in below 2 line  headers = { 'user-agent' : 'mozilla/4.0 (compatible; msie 5.5; windows nt)' } req = request('http://www.tastekid.com/api/similar?q=red+hot+chili+peppers%2c+pulp+fiction', headers = headers)   try:     response = urlopen(req) except urlerror e:     if hasattr(e, 'reason'):         print 'we failed reach server.'         print 'reason: ', e.reason     elif hasattr(e, 'code'):         print 'the server couldn\'t fulfill request.'         print 'error code: ', e.code else:     print 'everything fine' 
  • without headers

    $ python test.py  failed reach server. reason:  forbidde 
  • with headers

    $ python test.py  fine 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -