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>
File "C:UsersrnairAppDataLocalProgramsPythonPython35libsite-", line 455,  in load
 return loads(,
File "", 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):
 if xy=="Account Deleted":
try:      ''+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')

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.


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 ='yoururl')
if url.getcode() == 400:
  data1.append('Private Account')
  data2.append('Private Account')
  data3.append('Private Account')

Leave a Reply

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