Received 200 status code when running in REST API Explorer but 401 error code in Python

Kevin Nguyen
Kilo Explorer

Hello ServiceNow community,

I'm having an issue when running APIs from ServiceNow UI:

1. I tested API with UI -> System Web Services -> REST API Explorer and it returns status code 200.

2. But when I used the code sample from UI (Python) and inputted to ATOM to run (already changed username and password), I received error code 401 although I had the necessary roles for my account.

Please help me with this issue.

Thank you.

Best Regards.

12 REPLIES 12

Hitoshi Ozawa
Giga Sage
Giga Sage

Hi Kevin,

Does the user have privilege to access the table? If accessing ServiceNow via MID Server, MID server needs to be specified.

Check the following thread.

https://community.servicenow.com/community?id=community_question&sys_id=3ed69935db20a450fa192183ca96...

Hi Hitoshi,

Yes, user account has access to the tables (roles are mentioned in the attachments) and I'm using normal Windows machine to access ServiceNow, not via MID server.

Then it should work. I'm personally using pyCharm and was able to execute the following script.

I'm using Python 3.7.3. Try using the admin account.

def servicenow_get_test():
    # Need to install requests package for python
    # easy_install requests
    import requests

    instancename = '<instance name>'
    tablename = '<table name>'

    # Set the request parameters
    url = f"https://{instancename}.service-now.com/api/now/table/{tablename}>?sysparm_limit=1"

    # Eg. User name="admin", Password="admin" for this code sample.
    user = '<user name>'
    pwd = '<passwork>'

    # Set proper headers
    headers = {"Content-Type": "application/json", "Accept": "application/json"}

    # Do the HTTP request
    response = requests.get(url, auth=(user, pwd), headers=headers)

    # Check for HTTP codes other than 200
    if response.status_code != 200:
        print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:', response.json())
        exit()

    # Decode the JSON response into a dictionary and use the data
    data = response.json()
    print(data)

if __name__ == '__main__':
    servicenow_get_test()

Hi Hitoshi,

Unfortunately, I'm not owner of this instance, given that I could not use the admin account.

May I ask are there any further roles required to run APIs outside of ServiceNow UI? I'm still having 401 error code.

Hi,

Is it possible to the API from the web browser using the API uri? If this doesn't work, REST API may be disabled. 

Enter the following in the web browser to see if it returns a result. Substitute the {instancename} and {tablename}.

https://{instancename}.service-now.com/api/now/table/{tablename}>?sysparm_limit=1