TechOnTip Weblog

Run book for Technocrats

Service Now REST API and PowerShell

Posted by Brajesh Panda on March 28, 2016

Disclaimer… Neither am I a software developer nor a Service Now Guru. In the absence of our service now dev guy, I just got some time to play around with my powershell stuff. Just out of curiosity trying to learn how to work with REST API using Powershell.

Latest service now instances (starting with Eureka release) supports REST API. More info can be found here http://wiki.servicenow.com/index.php?title=REST_API#gsc.tab=0

There are tons of REST client resources in programming languages & dev guys understand them better. But as an infrastructure professional, without much of Dev knowledge, I play around with Powershell & bit with Chrome’s REST Extension. So “Invoke-RestMethod” cmdlet is my friend here. Note, Powershell 3.0 and above support this. I use latest one… 5.0 ;-). Just learned a new app from getpostman.com, https://www.getpostman.com/docs/introduction. These GUI tools are kind of cool to understand different parameters.

1. So Service Now REST API can be connected using two methods;

a. With Normal User ID & Password. Means every time you query, you need to send out both user ID & password for authentication. Although it goes thru HTTPS, it is little bit too much when you are doing all these stateless queries.

b. With Token based authentication. Starting with Service now’s Fuji release we can use Access Token to do all these queries. And this Access Token expires after certain time (default 30mins), then we can use another token called as Refresh Token with a fixed Client ID (like a weird string user name) & Client secret (like a complex password) to regenerate the Access Token.

2. Let’s see the powershell codes for 1(a) method.

# Query Incident Table and get maximum numbers of ticket

$URI = ‘https://techontip.service-now.com/api/now/table/incident?’

# OR Query Incident Table and get one ticket using sysparm query

# $URI = ‘https:// techontip.service-now.com/api/now/table/incident?sysparm_limit=1’

$SNowUser = “DomainUser” # If integrated with ADFS or any SAML Identity Source for SSO

$SNowPass = ConvertTo-SecureString –String “Password” –AsPlainText -Force

$SNowCreds = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $SNowUser, $SNowPass

$Incidents = Invoke-RestMethod -Uri $URI -Credential $SNowCreds -Body $Body -ContentType "application/json"

$Incidents.result.count

$Incidents.result[1]

3. For 1(b) method, you have to enable OAuth 2.0 thru service now portal. Here are the steps; http://wiki.servicenow.com/index.php?title=OAuth_Setup#gsc.tab=0

4. You may have to give yourself security admin role. I think I have that access in our Dev instance. I am going to figure that out later. As it is not my current priority, I have not checked those details.

5. Here is a screenshot. I created a new one for my Powershell Scripts.

In Service Now – Search “system oauth” – click on “application registry” – Click “new” – Select “Create an Oauth api endpoint for external clients” – configure necessary things..

6. Keep Client ID & Client Secret in a safe place. You may like to change Refresh token and access token time period as per our requirement.

7. Here is a nice video presentation from service now team using getpostman app. This one demonstrate how to generate refresh token & access token. And then how to use access token to retrieve data. But I am going to give you few line of Powershell codes here…

# Get Refresh token and Access Token using below script

$username = “DomainUsername”

$password = “Password”

$ClientID = “Paste Client ID from Step 6”

$ClientSecret = “Paste Client Secret from Step 6”

# Query REST Endpoint

$RestEndpoint = ‘https://techontip.service-now.com/oauth_token.do’

$body = [System.Text.Encoding]::UTF8.GetBytes(‘grant_type=password&username=’+$username+’&password=’+$password+’&client_id=’+$ClientID+’&client_secret=’+$ClientSecret)

Invoke-RestMethod -Uri $RestEndpoint -Body $Body -ContentType ‘application/x-www-form-urlencoded’ -Method Post

8. Output will be somewhat like below..

scope : useraccount

token_type : Bearer

expires_in : 1800

refresh_token : jsdfkajd;ewiorqjkfmsdkfamdfi;qirjqwkvm,c vkoejpmfklsdmfpiopioqijekmfd,kj7381893409mkas

access_token : sdnfok34u59834mdkfmaoiei4u398mlak;smr9i43uumaslkjripp98q347ja;k3ju409932mf;lkaj493q883

9. Now let’s use the access_token to retrieve data. We need to pass access_token thru headers as authorization. Do not forget that Bearer word to append before the access token.

# Query Incident Table and get maximum numbers of ticket

$URI = ‘https://techontip.service-now.com/api/now/table/incident?’

# OR Query Incident Table and get one ticket using sysparm query

# $URI = ‘https:// techontip.service-now.com/api/now/table/incident?sysparm_limit=1’

$headers = @{“authorization” = “Bearer sdnfok34u59834mdkfmaoiei4u398mlak;smr9i43uumaslkjripp98q347ja;k3ju409932mf;lkaj493q883”}

$result = Invoke-RestMethod -Uri $URI -Headers $headers

10. After 1800 seconds, the access_token will expire and we need a new one. We can use the step 7 or below codes with the existing refresh_token, client id & secret to get a new access_token.

# Get Access Token using Refresh Token.

$Refreshtoken = "jsdfkajd;ewiorqjkfmsdkfamdfi;qirjqwkvm,c vkoejpmfklsdmfpiopioqijekmfd,kj7381893409mkas"

$ClientID = “Paste Client ID from Step 6”

$ClientSecret = “Paste Client Secret from Step 6”

# Query REST Endpoint

$RestEndpoint = ‘https://techontip.service-now.com/oauth_token.do’

$body = [System.Text.Encoding]::UTF8.GetBytes(‘grant_type=refresh_token&client_id=’+$ClientID+’&client_secret=’+$ClientSecret+’&refresh_token=’+$refreshtoken)

Invoke-RestMethod -Uri $RestEndpoint -Body $Body -ContentType ‘application/x-www-form-urlencoded’ -Method Post

11. Output will be kind of same as step 8, with a different access_token. Then repeat step 9 using new access token.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: