How to avoid or skip error 400 in python while calling the API

Note:- I have written my code after referring to few examples in stack overflow but still could not get the required output

I have a python script in which loop iterates with an Instagram API. I give the user_id as an input to the API which gets the no of posts, no of followers and no of following. Each time it gets a response, I load it into a JSON schema and append to lists data1, data2 and data3.

The issue is:= Some accounts are private accounts and the API call is not allowed to it. When I run the script in IDLE Python shell, its gives the error

Traceback (most recent call last):
  File "<pyshell#144>", line 18, in <module>
beta=json.load(url)
File "C:UsersrnairAppDataLocalProgramsPythonPython35libsite-  packagessimplejson-3.8.2-py3.5-win-amd64.eggsimplejson__init__.py", line 455,  in load
 return loads(fp.read(),
File "C:UsersrnairAppDataLocalProgramsPythonPython35libtempfile.py", line 483, in func_wrapper
return func(*args, **kwargs)
**ValueError: read of closed file**

But the JSON contains this:-

{
  "meta":  {
  "error_type": "APINotAllowedError",
  "code": 400,
  "error_message": "you cannot view this resource"
 }
}

My code is:-

for r in range(307,601):
 var=r,sheet.cell(row=r,column=2).value
 xy=var[1]
 ij=str(xy)
 if xy=="Account Deleted":
    data1.append('null')
    data2.append('null')
    data3.append('null')
    continue
myopener=Myopen()
try:           
    url=myopener.open('https://api.instagram.com/v1/users/'+ij+'/?access_token=641567093.1fb234f.a0ffbe574e844e1c818145097050cf33')
except urllib.error.HTTPError as e:  // I want the change here
    data1.append('Private Account')
    data2.append('Private Account')
    data3.append('Private Account')
    continue
beta=json.load(url)
item=beta['data']['counts']
data1.append(item['media'])
data2.append(item['followed_by'])
data3.append(item['follows'])

I am using Python version 3.5.2. The main question is If the loop runs and a particular call is blocked and getting this error, how to avoid it and keep running the next iterations? Also, if the account is private, I want to append “Private account” to the lists.

Answer

Looks like the code that is actually fetching the URL is within your custom type – “Myopen” (which is not shown). It also looks like its not throwing the HTTPError you are expecting since your “json.load” line is still being executed (and leading to the ValueError that is being thrown).

If you want your error handling block to fire, you would need to check the response status code to see if its != 200 within Myopen and throw the HTTPError you are expecting instead of whatever its doing now.


I’m not personally familiar with FancyURLOpener, but it looks like it supports a getcode method. Maybe try something like this instead of expecting an HTTPError:

url = myopener.open('yoururl')
if url.getcode() == 400:
  data1.append('Private Account')
  data2.append('Private Account')
  data3.append('Private Account')
  continue

Leave a Reply

Your email address will not be published. Required fields are marked *