Search code examples
pythonamazon-web-servicesservicenow

How a Python script in AWS EC2 can communicate to ServiceNow REST API


I am trying to learn how to inform ServiceNow via REST API that I updated a record in MySQL (AWS RDS) using a Python script (in AWS EC2 Windows Server 2012) for it fetch that updated record. What particular Python libraries / modules should I learn to put me in the right direction?

Currently my Python script and MySQL RDS are communicating just fine.

I am still in the phase of trying to get a better understanding of REST API and AWS EC2.

Any other AWS, ServiceNow, or Python related information that could be share would be greatly appreciated.


Solution

  • The ServiceNow table REST API is very straightforward so inserting a record into an arbitrary table with Python is a breeze. For example:

    #Need to install requests package for python
    #easy_install requests
    import requests
    
    # Set the request parameters
    url = 'https://[instance name].service-now.com/api/now/table/[table name]'
    
    # Eg. User name="admin", Password="admin" for this code sample.
    user = 'admin'
    pwd = 'admin'
    
    # Set proper headers
    headers = {"Content-Type":"application/json","Accept":"application/json"}
    
    # Do the HTTP request - this is fake data
    response = requests.post(url, auth=(user, pwd), headers=headers ,data="[your json string of fields and values]")
    
    # 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)
    

    The REST API Explorer in ServiceNow if very useful for building and testing queries. It even generates sample code. You can search REST API Explorer in the navigator to find it.

    Another option is to create a Scripted REST API in ServiceNow to create a custom URL that you can hit to achieve the notification. This is good if you don't need to persist the data and just want to be notified.