Python REST Service Now API for text search - python

I am new to external scripting in Service Now.
I have this requirement of performing a text search in Service Now. I'm planning to insert the texts to be searched in a csv file and then through a python rest API of service now, perform the text search.
However, I was unable to find any direct python REST Service Now API to do text search. Does anyone know any alternative ways of doing this task?
Thanks in Advance!

You can use 'Global Text Search API' in ServiceNow platform to get search results. First you need to get the list of search groups available and then send a query with list of groups that need to be searched and the search keyword.
Here's a sample program that searched for keyword agent in Knowledge base and Service catalog.
import requests
# Set the request parameters
url = 'https://<instance>.service-now.com/api/now/v1/globalsearch/groups'
# 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
response = requests.get(url, auth=(user, pwd), headers=headers )
# 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)
url = 'https://<instance>.service-now.com/api/now/v1/globalsearch/search?sysparm_groups=2b77ce594bd6c0d901b8fbe25ceff671&sysparm_search=agent'
# Do the HTTP request
response = requests.get(url, auth=(user, pwd), headers=headers )
# 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)

Related

How get bearer token with requests from python

I'm trying to replicate a login to a page with python and the requests module but I need a token bearer.
This site doesn't require a login password connection but just an event code (wooclap.com)
I cannot find when the token is recovered by looking at header and json responses.
If you can help me
Thanks
once you put in a event code check the network tab on you're chrome console there should be a request wich returns the token. either in the reponse header or the json,
I'd recommend finding it using DevTools in your browser (F12).
In network you can see the login request mainly under headers and response. I've used this to implemented it below in python for you.
import requests
# Set the URL of the login page
url = "https://app.wooclap.com/api/auth/local/login"
# Set the login credentials
data = {"username": "< !!enter username here!! >", "password": "< !!enter password here!! >"}
# Send the login request and store the response
response = requests.post(url, data=data)
# Get the JSON response body
json_response = response.json()
# Get the AWT token from the JSON response
awt_token = json_response.get("token")
# Set the URL of the resource you want to access
url = "https://app.wooclap.com/public/events"
# Set the authorization header of your request, using the Bearer scheme
headers = {"Authorization": f"Bearer {awt_token}"}
# Send the request and store the response
response = requests.get(url, headers=headers)
print(response.text)
To send a GET request with a Bearer Token authorization header using Python, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header

Python Rest API, how to sign in to retieve data

I am trying to access a dataset from python available here
In the API documentation, there is no information on how to sign in using username and password via script. Upon manually entering the API URL into a browser
https://ev.caltech.edu/api/v1/sessions/caltech/ts
I have to manually enter the username: DEMO_TOKEN and password: <blank> and click on sign in to get the JSON response from the server.
How do I programmatically do that in python?
Below is my snippet which doesn't work
import requests
api_url = "https://ev.caltech.edu/api/v1/sessions/caltech/ts"
response = requests.get(api_url)
response.json()
Works for me, when I do this:
import requests
user = "DEMO_TOKEN"
passwd = ""
api_url = "https://ev.caltech.edu/api/v1/sessions/caltech/ts"
response = requests.get(api_url, auth=(user,passwd))
if response.status_code == 200:
print(response.json())
Please be warned, the json is HUGE.

Imgur API: 404 not found responses when photo does not belong to user's account

When I request images by hash from the imgur API I consistently get a 404 not found response, unless I supply a hash of an image uploaded to my personal account, then I receive a proper response. What may be the reason for that? Is there any way you can think of solving this? Thank you
header = {"Authorization": f"Client-ID {CLIENT_ID}"}
url1 = https://api.imgur.com/3/image/OhHNMos
request1 = requests.get(url1, headers=header)
print(request1.status_code) # 200
url2 = https://api.imgur.com/3/image/iFp46tO
request2 = requests.get(url2, headers=header)
print(request2.status_code) # 404

How to GET responde status code from get request?

Hi I am very new to python programming. Here I'm trying to write a python script which will get a status code using GET request. I can able to do it for single URL but how to do it for multiple URL's in a single script.
Here is the basic code I have written which will get response code from a url.
import requests
import json
import jsonpath
#API URL
url = "https://reqres.in/api/users?page=2"
#Send Get Request
response = requests.get(url)
if response:
print('Response OK')
else:
print('Response Failed')
# Display Response Content
print(response.content)
print(response.headers)
#Parse response to json format
json_response = json.loads(response.text)
print(json_response)
#Fetch value using Json Path
pages = jsonpath.jsonpath(json_response,'total_pages')
print(pages[0])
try this code.
import requests
with open("list_urls.txt") as f:
for url in f:
response = requests.get(url)
print ("The url is ",url,"and status code is",response.status_code)
I hope this helps.
You can acess to the status code with response.status_code
You can put your code in a function like this
def treat_url(url):
response = requests.get(url)
if response:
print('Response OK')
else:
print('Response Failed')
# Display Response Content
print(response.content)
print(response.headers)
#Parse response to json format
json_response = json.loads(response.text)
print(json_response)
#Fetch value using Json Path
pages = jsonpath.jsonpath(json_response,'total_pages')
print(pages[0])
And have a list of urls and iterate throw it:
url_list=["www.google.com","https://reqres.in/api/users?page=2"]
for url in url_list:
treat_url(url)
A couple of suggestions, the question itself is not very clear, so a good articulation would be useful for all the contributors over here :) ...
Now coming to what I was able to comprehend, there are few modifications that you can do:
response = requests.get(url) You will always get a response object, I think you might want to check the status code here, which you can do by response.status_code and based upon what you get, you say whether or not you got a success response.
and regarding looping, you can check the last page from response JSON as response_json['last_page'] and run a for loop on range(2, last_page + 1) and append the page number in URI to fetch individual pages response
You can directly fetch JSON from response object response.json()
Please refer to requests doc here

XML POST REST Request using Python

Does anyone have a simple example of sending an XML POST request to a RESTful API with Python? I am trying to use the urllib2 Python library to "create a new project" in the Harvest API, with no luck. The payload variable is a valid XML document that is a near copy/paste of their documentation (under the Create New Project heading) shown here:
http://www.getharvest.com/api/projects
Here is the code I am trying to execute.
def postRequest():
""" Makes POST request to url, and returns a response. """
url = 'http://subdomain.harvestapp.com/projects'
opener = urllib2.build_opener()
opener.addheaders = [('Accept', 'application/xml'),
('Content-Type', 'application/xml'),
('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password))[:-1]),
('User-Agent', 'Python-urllib/2.6')]
req = urllib2.Request(url=url, data=payload)
assert req.get_method() == 'POST'
response = self.opener.open(req)
print response.code
return response
I receive a response code 200 (Status OK) instead of a response code 201 (Created)...is this a question for the Harvest Support guys?
Any hints anyone has would be greatly appreciated.
Thanks,
Jeff.
It's common to return a 200 response even when a 201 response would strictly be more appropriate. Are you sure that the request isn't correctly processed even if you are getting a 'correct' response?
You're using a local opener everywhere except on the line where you create the response, where you use self.opener, which looks like the problem.

Categories

Resources