Python web services client examples
Summarize
Summary of Python web services client examples
This document provides practical Python examples for integrating with ServiceNow SOAP web services using the SOAPpy library. It demonstrates how to perform common operations such as creating incidents, querying records, retrieving keys, and advanced use cases like monitoring log files and creating ECC Queue records. The focus is on leveraging Python scripts to interact programmatically with ServiceNow instances for automation and integration purposes.
Show less
Requirements
- Python modules needed: fpconst, PyXML, and SOAPpy.
- Always use the web services URL format:
https://INSTANCE.service-now.com.
Key Examples and Use Cases
- Insert Incident: Script to create an incident record by passing parameters such as impact, urgency, priority, category, location, caller, assignment group, assigned to, short description, and comments.
- Get Keys: Retrieves sysids of incident records filtered by a specified category, demonstrating basic authentication and querying.
- Get Records: Fetches incident records matching a filter (e.g., category) and iterates over the results to access individual fields.
- Get Record by sysid: Retrieves a specific incident record using its unique sysid.
- Advanced ECC Queue Integration: Reads a log file to find lines matching a keyword ("invalid spi"), then creates ECC Queue records with XML payloads representing alerts. Includes error handling for file access and maintains state to process only new log entries.
Practical Considerations for ServiceNow Customers
- Use secure HTTPS URLs with correct instance naming to ensure proper connectivity.
- Authenticate with valid ServiceNow user credentials (username/password) that have appropriate permissions for the targeted tables.
- Enable debugging options in SOAPpy if needed to troubleshoot SOAP requests and responses.
- For advanced scripting scenarios, maintain state between runs (e.g., last processed log byte) to avoid duplicate processing.
- These examples illustrate how to automate incident management and event processing workflows by integrating Python scripts with ServiceNow’s SOAP API.
Expected Outcomes
By applying these examples, customers can programmatically create and query incident records, retrieve key identifiers, and automate alert ingestion into ServiceNow's ECC Queue. This facilitates efficient integration and automation of IT service management processes using Python-based clients.
Examples demonstrating an integration with a Python web services client.
Requirements
insert
#!/usr/bin/python
from SOAPpy import SOAPProxy
import sys
def createincident (params_dict ):
# instance to send to
instance = 'demo'
# username/password
username = 'itil'
password = 'itil'
# proxy - NOTE: ALWAYS use https://INSTANCE.service-now.com, not https://www.service-now.com/INSTANCE for web services URL from now on!
proxy = 'https://%s:%s@%s.service-now.com/incident.do?SOAP' % (username , password , instance )
namespace = 'http://www.service-now.com/'
server = SOAPProxy (proxy , namespace )
# uncomment these for LOTS of debugging output #server.config.dumpHeadersIn = 1 #server.config.dumpHeadersOut = 1 #server.config.dumpSOAPOut = 1 #server.config.dumpSOAPIn = 1
response = server. insert (impact = int (params_dict [ 'impact' ] ) , urgency = int (params_dict [ 'urgency' ] ) , priority = int (params_dict [ 'priority' ] ) , category =params_dict [ 'category' ] , location =params_dict [ 'location' ] , caller_id =params_dict [ 'user' ] , assignment_group =params_dict [ 'assignment_group' ] , assigned_to =params_dict [ 'assigned_to' ] , short_description =params_dict [ 'short_description' ] , comments =params_dict [ 'comments' ] )
return response
values = { 'impact': '1' , 'urgency': '1' , 'priority': '1' , 'category': 'High' , 'location': 'San Diego' , 'user': 'fred.luddy@yourcompany.com' , 'assignment_group': 'Technical Support' , 'assigned_to': 'David Loo' , 'short_description': 'An incident created using python, SOAPpy, and web services.' , 'comments': 'This a test making an incident with python.\n Isn \' t life wonderful?' }
new_incident_sysid =createincident (values )
print "Returned sysid: "+ repr (new_incident_sysid )getKeys
#!/bin/env python
# use the SOAPpy module from SOAPpy import SOAPProxy
username , password , instance = 'admin' , 'admin' , 'demo'
proxy , namespace = 'https://username:password@www.service-now.com/'+instance+ '/incident.do?SOAP' , 'http://www.service-now.com/'
server = SOAPProxy (proxy ,namespace )
response = server. getKeys (category = 'Network' )
print response. sys_id. split ( ',' )getRecords
#!/bin/env python
# use the SOAPpy module from SOAPpy import SOAPProxy
username , password , instance = 'admin' , 'admin' , 'demo'
proxy , namespace = 'https://username:password@www.service-now.com/'+instance+ '/incident.do?SOAP' , 'http://www.service-now.com/'
server = SOAPProxy (proxy ,namespace )
response = server. getRecords (category = 'Network' )
for record in response:
for item in record:
print itemget
sys_id (with basic
authentication).#!/bin/env python
# use the SOAPpy module from SOAPpy import SOAPProxy
username , password , instance = 'admin' , 'admin' , 'demo'
proxy , namespace = 'https://username:password@www.service-now.com/'+instance+ '/incident.do?SOAP' , 'http://www.service-now.com/'
server = SOAPProxy (proxy ,namespace )
response = server. get (sys_id = '9c573169c611228700193229fff72400' )
for each in response:
print eachAdvanced
#!/bin/env python
# kevin.pickard@service-now.com 2008.07.03 initial creation
from SOAPpy import SOAPProxy
from xml. dom. minidom import getDOMImplementation
import sys , os , socket , pickle , re
# instance to send to
instance = 'demo'
# username/pass
username = 'admin'
password = 'admin'
# log file to watch
syslogfile = '/var/log/cisco.log.ksp'
# state file
statefile = '/tmp/syslog_ecc.state-test'
# ECC queue values
soapagent = 'SOAPpy'
ecctopic = 'PIX Error: '
eccname = 'Invalid SPI: '
eccsource = 'Syslog'
# regex string to match
matchstring = 'invalid spi'
try:
state = open (statefile , 'r' )
lastbyte = pickle. load (state )
state. close ( ) except:
lastbyte = 0
#print 'DEBUG: lastbyte = '+str(lastbyte)
try:
log = open (syslogfile , 'ro' ) except:
errortopic = 'Script Error'
errorname = 'Unable to open log file '+syslogfile+ '.'
errorpayload = 'This message was generated due to an error condition encountered in a script. The name of the script is '+ os. path. basename ( sys. argv [ 0 ] )+ ' on server '+ socket. gethostname ( )+ '.'
proxy = 'https://'+username+ ':'+password+ '@'+instance+ '.service-now.com/ecc_queue.do?SOAP'
namespace = 'http://www.service-now.com/'
server = SOAPProxy (proxy , namespace )
server. config. dumpSOAPOut = 1
server. config. dumpSOAPIn = 1
response = server. insert (agent =soapagent , topic =errortopic , name =errorname , source = sys. argv [ 0 ] , payload =errorpayload )
sys. exit ( 1 )
if lastbyte != 0:
try:
log. seek (lastbyte ) except IOError:
pass
loglines =log. readlines ( )
lastbyte =log. tell ( )
log. close ( )
state = open (statefile , 'w' ) pickle. dump (lastbyte , state )
state. close ( )
# regex out the line
matchedlines = [ ] for line in loglines:
if re. search (matchstring , line ) != None:
matchedlines. append (line )
#print 'DEBUG: len->loglines = '+str(len(loglines)) #print 'DEBUG: lastbyte = '+str(lastbyte) #print 'DEBUG: matchedlines = '+str(matchedlines)
if len (matchedlines ) == 0:
sys. exit ( 0 )
proxy = 'https://'+username+ ':'+password+ '@'+instance+ '.service-now.com/ecc_queue.do?SOAP'
namespace = 'http://www.service-now.com/'
server = SOAPProxy (proxy , namespace ) #server.config.dumpSOAPOut = 1 #server.config.dumpSOAPIn = 1
entriestosend = { } for line in matchedlines:
device =line. split ( ) [ 3 ]
sourceip =line. split ( ) [- 1 ]
entriestosend [sourceip ] = [device , line ]
for key ,value in entriestosend. iteritems ( ):
#impl=getDOMImplementation() #newdoc = impl.createDocument(None, "log_line", None) #top_element = newdoc.documentElement #text = newdoc.createTextNode(value[1]) #top_element.appendChild(text)
response = server. insert (agent =soapagent , topic =ecctopic+value [ 0 ] , name =eccname+key , source =eccsource , payload =value [ 1 ] )