Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bryanbarnard/2f6a29339a81f7ebcb262b300b52b77c to your computer and use it in GitHub Desktop.
Save bryanbarnard/2f6a29339a81f7ebcb262b300b52b77c to your computer and use it in GitHub Desktop.
ServiceNow REST Attachment API Example Python Example using /now/attachment/upload endpoint to post (upload) a file as an attachment to an incident as multipart form data.
# This example uses the Python Requests Library and you will need to install requests package for python
# Documentation can be found at http://docs.python-requests.org/en/master/user/quickstart/
import requests
import pprint
import json
# Specify the Endpoint URL replacing {servicenow_instance_name} with your ServiceNow Instance Name
url = 'https://{servicenow_instance_name}.service-now.com/api/now/attachment/upload'
# Specify Parameters for File Being Uploaded, the table_name and table_sys_id should be replaced with values that make
# sense for your use case
payload = {'table_name':'incident', 'table_sys_id':'81f8915bdb6ba20028927416bf961971'}
# Specify Files To Send and Content Type. When specifying fles to send make sure you specify the path to the file, in
# this example the file was located in the same directory as the python script being executed.
# it is important to specify the correct file type
files = {'file': ('issue_screenshot.JPG', open('issue_screenshot.JPG', 'rb'), 'image/jpg', {'Expires': '0'})}
# Eg. User name="admin", Password="admin" for this code sample. This will be sent across as basic authentication
user = 'admin'
pwd = 'admin'
# Set proper headers
headers = {"Accept":"*/*"}
# Send the HTTP request
response = requests.post(url, auth=(user, pwd), headers=headers, files=files, data=payload)
# Check for HTTP codes other than 201
if response.status_code != 201:
print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
exit()
# Print Resopnse Details
print 'Response Status Code:', response.status_code
print ''
print('Reponse Payload:')
print json.dumps(response.json(), indent=4)
@huita21
Copy link

huita21 commented Feb 2, 2022

thank you for this sample! I tried to use servicenow sample code to call REST API, the file open/write step always failed. the sample code helped me figure out why, upload is now working for me:-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment