As I cannot see any reference on how to use properly the sysparm_query_category, may I confirm on how did you append the sysparm_query_category in get request?
Added below line of codes. I hope someone can help and guide me as I'm new to ServiceNow. Thanks!
from pysnow import Client
...
resource = self.client.resource(api_path=F"/table/{table}")
resource.parameters.add_custom({"sysparm_query_category": "cat_read_generic"})
request = resource.get(query=query, fields=fields)
https://developer.servicenow.com/dev.do#!/reference/api/sandiego/rest/c_TableAPI
I am not aware pysnow API. I hope this helps. Else refer to the comment above.
#Need to install requests package for python
#easy_install requests
import requests
# Set the request parameters
url = 'https://demonightlycoe.service-now.com/api/now/table/incident?sysparm_query=category%3Dcat_read_generic&sysparm_limit=1'
# 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)
Upon checking and testing, we can use the add_custom
client.parameters.add_custom({'foo': 'bar'})
that would be additional to the parameters like &foo=bar
https://pysnow.readthedocs.io/en/latest/usage/parameters.html
Related
I need to print all requests from specific Postman collection. I have this code:
import requests
# Set up Postman API endpoint and authorization
postman_api_endpoint = "https://api.getpostman.com/collections"
postman_api_key = "PMAK-63b6bf724ebf902ad13d4bf2-e683c12d426716552861acda**********"
headers = {"X-Api-Key": postman_api_key}
# Get all requests from Postman collection
collection_id = "25184041-c1537769-f598-4c0e-b8ae-8cd185a79c03"
response = requests.get(f"{postman_api_endpoint}/{collection_id}/items", headers)
if response.status_code != 200:
print("Error retrieving collection:", response.text)
else:
# Print all requests
requests_data = response.json()["items"]
for request_data in requests_data:
request_method = request_data["request"]["method"]
request_url = request_data["request"]["url"]
request_headers = request_data["request"]["header"]
request_body = request_data["request"]["body"]["raw"] \
if request_data["request"]["body"]["mode"] == "raw" else ""
print(f"{request_method} {request_url}")
print("Headers:")
for header in request_headers:
print(f"{header['key']}: {header['value']}")
print("Body:")
print(request_body)
I received an error while I try to call response.text and have such massage:
Error retrieving collection: {"error":{"name":"notFound","message":"Requested resource not found"}}
Which means that I have 404 error. I have several assumptions what I did wrong:
I entered incorrect api key(But I checked several times and regenerated it twice)
I entered incorrect collection id, but in the screen below you can see where I took it and it is correct
And as I think the most likely variant I wrote incorrect request where I put my key and my collection id(I din't find any example how such requests should be like)
And of course I have requests in my collection, so error can not be because the collection is empty
Please give me some advice how I can fix this error. Thank you!
The answer is actually is really simple. I didn't know that I need to push button save request in Postman. I think if I create request in collection it will automatically save it. But I didn't, so I just saved all requests manually and finally receive correct response.
I am trying to set up a notification from on a payment. Here is my code:
def PayPal_IPN():
'''This module processes PayPal Instant Payment Notification messages (IPNs).'''
# Switch as appropriate
VERIFY_URL_PROD = 'https://ipnpb.paypal.com/cgi-bin/webscr'
VERIFY_URL = VERIFY_URL_PROD
# Read and parse query string
params = request.form.to_dict()
# Add '_notify-validate' parameter
params['cmd'] = '_notify-valudate'
# Post back to PayPal for validation
headers = {'content-type': 'application/x-www-form-urlencoded',
'user-agent': 'Python-IPN-Verification-Script'}
r = requests.post(VERIFY_URL, params=params, headers=headers, verify=True)
r.raise_for_status()
# Check return message and take action as needed
if r.text == 'VERIFIED':
print("SUCCESSFULL")
elif r.text == 'INVALID':
print("FAILURE")
else:
print("NOTHING HAPPENED?")
return ""
Here is my error message:
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://ipnpb.paypal.com/cgi-bin/webscr....
Can someone help me figure out what I am not understanding? maybe the link has changed?
Here is the documentation I'm looking at https://developer.paypal.com/api/nvp-soap/ipn/IPNIntro/
I've tried changing the ipnpb to www. and still no luck.
The problem is the format of params. I'm not sure what request.form.to_dict() returns, but I do know that when you add cmd=_notify_validate it should be in this format:
params.append(('cmd', '_notify-validate'))
Also returning the appropriate format is urllib.parse.parse_qsl
this is my first ever question on here.
Currently I am looking into the Python requests module. I am trying to automate a task for which i need to pass on a csrf token.
The csrf token can be found in the payload of a previous request.
How can I extract the value out of the Payload?
Example Payload:
value1: ABCD
value2: EFGH
csrf_token: the token I am looking for
value3: false
Sorry if this is a dumb or easy question but I am not able to solve it right now.
Thanks for your help!
Here are some examples of where the data you might be looking for is located.
import requests
response = requests.get('http://some_url')
# raise an exception if the status code != 200
response.raise_for_status()
# the contents of the response. (bytes)
contents = response.contents
# the contents of the response if the contents are
# formatted as JSON. (dictionary)
contents = response.json()
# the headers of the response. (dictionary)
headers = response.headers
# You also have to consider if you are using the correct HTTP protocol
payload = {}
response = requests.put('http://some_url', json=payload)
response = requests.post('http://some_url', json=payload)
# the responses are going to function just like when using the "get" protocol
I am working with an API from SignalHire. The API docs reference a callback URL but I don't have a very technical background and am not sure how to set this up. I've done some digging but I am still very confused and not sure how to proceed. Here is my code:
API_KEY = 'testapikey'
headers = {'apikey': API_KEY,
'callbackUrl': ''}
data = {'items': ['https://www.linkedin.com/in/testprofile/']}
response = requests.post("https://www.signalhire.com/api/v1/candidate/search", headers=headers, json=data)
if response.status_code == 200:
print(json.dumps(response.json(), sort_keys=True, indent=4))
I just need help understanding what a callback url is and how I can set that up.
When you post the search request, you won't get back results immediately. Instead, you'll get a 201 response that lets you know that SignalHire has received your request.
When the results are ready, they will be posted to the the URL you provide. It should be an endpoint that you write that sends a 200 response back to SignalHire acknowledging that it has received the search results.
I'm using the python requests module to handle requests on a particular website i'm crawling. I'm fairly new to HTTP requests, but I do understand the basics. Here's the situation. There's a form I want to submit and I do that by using the post method from the requests module:
# I create a session
Session = requests.Session()
# I get the page from witch I'm going to post the url
Session.get(url)
# I create a dictionary containing all the data to post
PostData = {
'param1': 'data1',
'param2': 'data2',
}
# I post
Session.post(SubmitURL, data=PostData)
Is there a any ways to check if the data has been successfully posted?
Is the .status_code method a good way to check that?
If you pick up the result from when you post you can then check the status code:
result = Session.post(SubmitURL, data=PostData)
if result.status_code == requests.codes.ok:
# All went well...
I am a Python newbie but I think the easiest way is:
if response.ok:
# whatever
because all 2XX codes are successful requests not just 200
I am using this code:
import json
def post():
return requests.post('http://httpbin.org/post', data={'x': 1, 'y': 2})
def test_post(self):
txt = post().text
txt = json.loads(txt)
return (txt.get("form") == {'y': '2', 'x': '1'})
For POST responses, the response status code is usually 201 (especially with RestAPIs) but can be 200 sometimes as well depending on how the API has been implemented.
There are a few different solutions:
Solution #1 (use the framework to raise an error) - Recommended:
from requests.exceptions import HTTPError
try:
response = Session.post(SubmitURL, data=PostData)
# No exception will raised if response is successful
response.raise_for_status()
except HTTPError:
# Handle error
else:
# Success
Solution #2 (explicitly check for 200 and 201):
from http import HttpStatus
response = Session.post(SubmitURL, data=PostData)
if response.status_code in [HttpStatus.OK, HttpStatus.CREATED]:
# Success
Solution #3 (all 200 codes are considered successful):
from http import HttpStatus
response = Session.post(SubmitURL, data=PostData)
if response.status_code // 100 == 2:
# Success