Accessing ServiceNow APIs using token method but not username and password

nateross1
Kilo Contributor

Trying to access ServiceNow APIs securely from a 3rd party.  The Python script below works but we need it to work using refresh_token, because of the security issues of providing a username and password in a scirpt.  Does someone have an example where we can use refresh_token instead of username/password?  Or what is the use of calling an API with a token if you're using a username and password to get the token?

#easy_install requests
import requests

from oauthlib.oauth2 import LegacyApplicationClient
from requests_oauthlib import OAuth2Session
import os

client_id = 'xxxxxxxxxxxxxx'
client_secret = 'xxxxxxxxx'
username = 'xxxxxx'
password = 'xxxxxx'

oauth = OAuth2Session(client=LegacyApplicationClient(client_id=client_id))
  
token = oauth.fetch_token(token_url='https://service-nowinstance/oauth_token.do',
       username=username, password=password,
    client_id=client_id,
      client_secret=client_secret,
  refresh_token='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')


access_token = token["access_token"]

# Set the request parameters
url = 'http://service-nowinstance/api/now/table/tablename

# Set proper headers
headers = {"Authorization": "Bearer "+access_token, "Content-Type":"application/json","Accept":"application/json"}
print ("headers = ", headers)

# Do the HTTP request
response = requests.post(url, headers=headers, data='{"columnname":"data"}' )

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

1 REPLY 1

nateross1
Kilo Contributor

I got it.  Please verify and mark as correct. 

To get the access token using Python:

import requests

url = "https://(service-now-instance-url)/oauth_token.do"

 

payload = "grant_type=password&client_id=(client id here)&client_secret=(client secret here)&username=(username here)&password=(password here)”

headers = {

    'Content-Type': "application/x-www-form-urlencoded",

    'Cache-Control': "no-cache"

    }

 

response = requests.request("POST", url, data=payload, headers=headers)

 

print(response.text)

 

 

To post a record in a table using Python and the access token:

 

import requests

url = "http://(service-now-instance-url)/api/now/table/(table name here)"

payload = "{\"(column)\":\"(column value)\",\"(column)\":\"(column value)\",\"(column)\":\"(column value)\"}"

headers = {

    'Content-Type': "application/json",

    'Authorization': "Bearer (access token here)",

    'Cache-Control': "no-cache"

    }

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text)