REST not working on instance

allanmullan
Kilo Explorer

I'm looking at moving an application that I wrote to integrate Nagios with Service Now using Python from SOAP to REST and have run into a bit of a stumbling block.

Basically, going by the example on the SN docs, the below should work:

import requests
import json

# Set the request parameters
url = 'https://xxx.service-now.com/api/now/table/incident'
user = 'xxx'
pwd = 'xxx'

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

# Do the HTTP request
response = requests.post(url, auth=(user, pwd), headers=headers , data = '{"short_description": "test"}')

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

# Decode the JSON response into a dictionary and use the data
print('Status:',response.status_code,'Headers:',response.headers,'Response:',response.json())

But instead I get:

 File "./REST.py", line 23, in         print('Status:',response.status_code,'Headers:',response.headers,'Response:',response.json())
   File "/usr/lib/python2.7/site-packages/requests/models.py", line 733, in json
       return json.loads(self.text, **kwargs)
   File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
       return _default_decoder.decode(s)
   File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
       obj, end = self.raw_decode(s, idx=_w(s, 0).end())
   File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
       raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

I've double checked and the user account definitely has REST permissions and GET works absolutely fine. I've also tried putting all required information into the data input but it makes no difference. Also, I tried using the servicenow_rest library available from pip it seems I'm just not getting no return data.

Is this just something odd with the ServiceNow instance? Using the Chrome extension works for REST queries so guessing not?

Cheers,

Allan

28 REPLIES 28

sergiu_panaite
ServiceNow Employee
ServiceNow Employee

Hello Allan,



I tried your python post on my own instance and it works fine.


The error you are getting is most probably related to invalid JSON data retrieved from server.



Can you dump/print/save the raw JSON before trying to decode?



Also can you try using simplejson library instead of json?



You can install simplejson using:



sudo pip install simplejson



and you import the library like:



import json as simplejson



Regards,
Sergiu


Hey Sergiu,



I dumped the raw data using response.raw.read(30) and there's nothing, it's like it's not returning anything. Tried using simplejson but get the following error:



Traceback (most recent call last):


  File "./REST.py", line 25, in <module>


      print('Status:',response.status_code,'Headers:',response.headers,'Response:',response.json())


  File "/usr/lib/python2.7/site-packages/requests/models.py", line 733, in json


      return json.loads(self.text, **kwargs)


  File "/usr/lib/python2.7/site-packages/simplejson/__init__.py", line 505, in loads


      return _default_decoder.decode(s)


  File "/usr/lib/python2.7/site-packages/simplejson/decoder.py", line 370, in decode


      obj, end = self.raw_decode(s)


  File "/usr/lib/python2.7/site-packages/simplejson/decoder.py", line 400, in raw_decode


      return self.scan_once(s, idx=_w(s, idx).end())


simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)



I'm not sure I'm getting anything back from ServiceNow which is odd. A ticket does get generated though so it's definitely getting through. Oh, and just an FYI - I'm getting a 201 response code...


Hello Allan,



To make sure you get output from response.raw.read(30) you need to have "stream=True" in your initial request, like:



response = requests.post(url, auth=(user, pwd), headers=headers, data='{"short_description":"Test"}', stream=True)



But this will only prove that you get data back (which can be already confirmed by your HTTP 201 code).


It might be here that we are dealing with incompatible character encoding, which means we might need to replace the quotes (possible other characters) of the data body.



What happens if you print your response in text format, like below. Does it works?



>>> import requests


>>> import json as simplejson


>>> url = 'https://myinstance.service-now.com/api/now/table/incident'


>>> user = 'admin'


>>> pwd = 'xxxxx'


>>> headers = {"Content-Type":"application/json", "Accept":"application/json"}


>>> response = requests.post(url, auth=(user, pwd), headers=headers, data='{"short_description":"Test"}' )


>>> response.json()


{u'result': {u'user_input': u'', u'sys_updated_by': u'admin', u'activity_due': u'', u'watch_list': u'', u'follow_up': u'', u'made_sla': u'true', u'delivery_task': u'', u'number': u'INC0010054', u'group_list': u'', u'correlation_id': u'', u'sys_mod_count': u'0', u'notify': u'1', u'resolved_by': u'', u'assigned_to': u'', u'closed_at': u'', u'category': u'inquiry', u'sla_due': u'', u'upon_approval': u'proceed', u'impact': u'3', u'close_notes': u'', u'expected_start': u'', u'knowledge': u'false', u'opened_by': {u'link': u'https://myinstance.service-now.com/api/now/table/sys_user/6816f79cc0a8016401c5a33be04be441', u'value': u'6816f79cc0a8016401c5a33be04be441'}, u'calendar_stc': u'', u'caused_by': u'', u'comments': u'', u'problem_id': u'', u'priority': u'5', u'state': u'1', u'sys_id': u'7e329deb2b4dc20090aa3ea3b4da150c', u'opened_at': u'2015-07-10 13:30:02', u'location': u'', u'work_notes': u'', u'work_start': u'', u'comments_and_work_notes': u'', u'time_worked': u'', u'sys_created_by': u'admin', u'upon_reject': u'cancel', u'reassignment_count': u'0', u'child_incidents': u'0', u'sys_tags': u'', u'sys_class_name': u'incident', u'delivery_plan': u'', u'description': u'', u'parent': u'', u'business_duration': u'', u'rfc': u'', u'company': u'', u'sys_updated_on': u'2015-07-10 13:30:02', u'approval_history': u'', u'cmdb_ci': u'', u'approval_set': u'', u'resolved_at': u'', u'calendar_duration': u'', u'caller_id': u'', u'active': u'true', u'approval': u'not requested', u'parent_incident': u'', u'sys_domain_path': u'/', u'closed_by': u'', u'severity': u'3', u'incident_state': u'1', u'reopen_count': u'0', u'subcategory': u'', u'due_date': u'', u'contact_type': u'phone', u'skills': u'', u'work_end': u'', u'work_notes_list': u'', u'sys_created_on': u'2015-07-10 13:30:02', u'escalation': u'0', u'correlation_display': u'', u'close_code': u'', u'short_description': u'Test', u'assignment_group': u'', u'sys_domain': {u'link': u'https://myinstance.service-now.com/api/now/table/sys_user_group/global                                                   ', u'value': u'global                                                   '}, u'business_stc': u'', u'order': u'', u'urgency': u'3'}}


>>> response.text


u'{"result":{"skills":"","upon_approval":"proceed","location":"","expected_start":"","reopen_count":"0","close_notes":"","impact":"3","urgency":"3","correlation_id":"","sys_tags":"","sys_domain":{"link":"https://myinstance.service-now.com/api/now/table/sys_user_group/global                                                   ","value":"global                                                   "},"description":"","group_list":"","priority":"5","delivery_plan":"","sys_mod_count":"0","work_notes_list":"","follow_up":"","closed_at":"","sla_due":"","delivery_task":"","sys_updated_on":"2015-07-10 13:30:02","parent":"","work_end":"","number":"INC0010054","closed_by":"","work_start":"","calendar_stc":"","business_duration":"","category":"inquiry","incident_state":"1","activity_due":"","correlation_display":"","company":"","active":"true","due_date":"","assignment_group":"","caller_id":"","knowledge":"false","made_sla":"true","comments_and_work_notes":"","parent_incident":"","state":"1","user_input":"","sys_created_on":"2015-07-10 13:30:02","approval_set":"","reassignment_count":"0","rfc":"","child_incidents":"0","opened_at":"2015-07-10 13:30:02","short_description":"Test","order":"","sys_updated_by":"admin","resolved_by":"","notify":"1","upon_reject":"cancel","approval_history":"","problem_id":"","work_notes":"","calendar_duration":"","close_code":"","sys_id":"7e329deb2b4dc20090aa3ea3b4da150c","approval":"not requested","caused_by":"","severity":"3","sys_created_by":"admin","resolved_at":"","assigned_to":"","business_stc":"","sys_domain_path":"/","cmdb_ci":"","opened_by":{"link":"https://myinstance.service-now.com/api/now/table/sys_user/6816f79cc0a8016401c5a33be04be441","value":"6816f79cc0a8016401c5a33be04be441"},"subcategory":"","sys_class_name":"incident","watch_list":"","time_worked":"","contact_type":"phone","escalation":"0","comments":""}}'


>>>



Regards,


Sergiu


Hi Sergiu,



That's exactly what I've been doing which has been causing the errors.



Quite frustrating issue as this is basically the same script ServiceNow use on their documentation and yet it just doesn't seem to work. I've also tried both Python 2 and 3.



Regards,


Allan