Python - Error when updating value in dict using API - python

I am trying to update some data using API.
I am able to successfully update if is a simple field. However some of the fields that I am trying to update are dictionary, so I am having issues updating such fields.
Given below is how my data is:
emp_id, emp_name, pay_data
emp_101, Scott, {'annualSalary': 0.0, 'baseRate': 0.0}
If I were to update the prod_name I do the below
url = "https://api.paylocity.com/api/v2/companies/B123/employees/emp_101/?grant_type=client_credentials&scope=WebLinkAPI&client_id=client_id&client_secret=client_secret"
payload = {'emp_name': 'Kevin'}
headers = {'Authorization': 'Bearer ' + access}
response = requests.request("PATCH", url, headers=headers, json=payload)
The code works just well.
However if I need to update anything in the pay_data field as below I get error code 400
url = "https://api.paylocity.com/api/v2/companies/B123/employees/emp_101/?grant_type=client_credentials&scope=WebLinkAPI&client_id=client_id&client_secret=client_secret"
payload = {'annualSalary': '100.0'}
headers = {'Authorization': 'Bearer ' + access}
response = requests.request("PATCH", url, headers=headers, json=payload)

I think you should convert from string to integer in basePrice
I mean like this payload = {'basePrice': 101} from '101'(string) to 101(integer)
Code:
url = 'www.website.com'
payload = {'basePrice': 101}
headers = {'Authorization': 'Bearer ' + access}
response = requests.request("PATCH", url, headers=headers, json=payload)

Related

trying to make an Yelp API call with a list of business IDs

When I run the code it's giving me this syntax error:
requests.exceptions.MissingSchema: Invalid URL 'h': No scheme supplied. Perhaps you meant http://h?
Here is the code I am working with:
from yelp_api_key import YELP_KEY
from yelp_api_location import loc_ids
MY_API_KEY = YELP_KEY
BUSINESS_PATH = f'https://api.yelp.com/v3/businesses/{loc_ids}/reviews'
HEADERS = {'Authorization': 'bearer %s' % MY_API_KEY}
PARAMETERS = {'locale': 'en_US'
}
for links in BUSINESS_PATH:
response = requests.get (url=links,
params=PARAMETERS,
headers=HEADERS)
business_data = response.json()
data = business_data['reviews']
print(data)
for x in data:
quotes = (x['text'])
print(quotes)
Below is the code that is working for me. I just want to be able to call multiple APIs without having to list the endpoints every time. Any suggestions would be great, TIA!
MY_API_KEY = YELP_KEY
BUSINESS_PATH = [f'https://api.yelp.com/v3/businesses/eL4d1tHv1mFoepoS_3rGbw/reviews',
f'https://api.yelp.com/v3/businesses/RzS-wNTycqB5WA34JfgW0g/reviews',
f'https://api.yelp.com/v3/businesses/PyV1e_OebaWm1cGUwtDvHA/reviews',
f'https://api.yelp.com/v3/businesses/dcbALMl6oyv_fdJ6dZGxzA/reviews',
f'https://api.yelp.com/v3/businesses/4uRA53NIl82a3QeZX-PcRw/reviews']
HEADERS = {'Authorization': 'bearer %s' % MY_API_KEY}
PARAMETERS = {'locale': 'en_US'
}
reviews = []
for links in BUSINESS_PATH:
# file_name = uuid.uuid1 ()
response = requests.get (url=links,
params=PARAMETERS,
headers=HEADERS)
business_data = response.json()
data = business_data['reviews']
for x in data:
quotes = (x['text'])
# print(quotes)
reviews.append(quotes)

how to insert a variable in xml payload data and get the response

I am new in python. I need to get the data based via url. The data is based on a unique number which is in payload. I can't seem to find a way to initiate a variable in "CUSTNO" in payload and iterate it. iterate it.
(I have removed some of the payload data)
url = 'url'
payload = "<CHANNELID></CHANNELID>\r\n </FCDB_HEADER>\r\n <FCDB_BODY>\r\n <CUSTOMER>\r\n " \
"<CUSTNO>123456789</CUSTNO>\r\n </CUSTOMER>\r\n"
response = requests.request("POST", url, data=payload, headers=headers)
xml_response = response.text
print(xml_response)
Below (assuming that you want to change the customer number)
url = 'url'
customer_no = 4562
payload = "<CHANNELID></CHANNELID>\r\n </FCDB_HEADER>\r\n <FCDB_BODY>\r\n <CUSTOMER>\r\n " \
"<CUSTNO>{}</CUSTNO>\r\n </CUSTOMER>\r\n"
response = requests.request("POST", url, data=payload.format(customer_no), headers=headers)
xml_response = response.text
print(xml_response)
Your question is really unclear!
Maybe your payload formatting is wrong. Which version of Python are you using?
Try this:
payload = '''<CHANNELID></CHANNELID>\r\n </FCDB_HEADER>\r\n <FCDB_BODY>\r\n <CUSTOMER>\r\n \
<CUSTNO>123456789</CUSTNO>\r\n </CUSTOMER>\r\n'''

400 respone from Azure Computer Vision API

I have a problem with Computer Vision resource on Azure. This code is based on documentation example and it already worked.(https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts/python-disk)
Suddenly i started getting 400 error:
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://nameofmyresource.cognitiveservices.azure.com/vision/v2.0/analyze?visualFeatures=Objects%2CTags
My piece of code:
for img_path in img_path_list:
image_data = open(img_path, "rb").read()
print(image_data)
headers = {'Ocp-Apim-Subscription-Key': subscription_key,
'Content-Type': 'application/octet-stream'}
params = {'visualFeatures': 'Objects,Tags'}
response = requests.post(
analyze_url, headers=headers, params=params, data=image_data)
response.raise_for_status()
analysis = response.json()
I've printed image_data (seems okay) and created new resource - nothing. Any thoughts?
Seems the url you are generating is wrong, Can you try the following code,
apikey = "e720e03190c41148ec555889daf2f64"
assert apikey
api_url = "https://southeastasia.api.cognitive.microsoft.com/vision/v2.0/"
analyse_api = api_url + "analyze"
image_data = img
headers = {"Ocp-Apim-Subscription-Key": apikey,
'Content-Type': 'application/octet-stream'}
params = {'visualFeatures':'Categories,Description,Color,Objects,Faces'}
response = requests.post(
analyse_api, headers=headers, params=params, data=image_data)
response.raise_for_status()
analysis = response.json()
#image_caption = analysis["description"]["captions"][0]["text"].capitalize()
people = 0
for i in analysis['objects']:
if i['object'] == 'person':
people += 1
describepeople = []
for i in analysis['faces']:
describepeople.append(i['gender'] + ' ' + str(i['age']))
tags = analysis['description']['tags']
return[people, describepeople, tags]
Something was bad with particular photo - next photo was okay

I can't openning a session in ALM 12.5x

I'am new in ALM. I just read some guides from REST API and try to repeat this. But I face up to the situation. In my last request I have 401 return (User not authenticated). What am I doing wrong?
import requests
from requests.auth import HTTPBasicAuth
url = "https://almalmqc1250saastrial.saas.hpe.com"
login = "+++++++"
password = "+++++"
cookies = dict()
headers = {}
r = requests.get(url + "/qcbin/rest/is-authenticated")
print(r.status_code, r.headers.get('WWW-Authenticate'))
r = requests.get(url + "/qcbin/authentication-point/authentication",
auth=HTTPBasicAuth(login, password), headers=headers)
print(r.status_code, r.headers)
cookie = r.headers.get('Set-Cookie')
LWSSO_COOKIE_KEY = cookie[cookie.index("=") + 1: cookie.index(";")]
cookies['LWSSO_COOKIE_KEY'] = LWSSO_COOKIE_KEY
print(cookies)
r = requests.post(url + "/qcbin/rest/site-session", cookies=cookies)
print(r.status_code, r.headers)
The solution was found. The problem is incorrect URL. To authentication you need this URL:
url_log = "https://login.software.microfocus.com/msg/actions/doLogin.action"
And you need this headers:
self.__headers = {
"Content-Type": "application/x-www-form-urlencoded",
'Host': 'login.software.microfocus.com'
}
The POST request to authenticate will be next:
r = self.__session.post(self.url_log, data=self.input_auth, headers=self.__headers)
Where data is:
self.input_auth = 'username=' + login + '&' + 'password=' + password

request returns status 404 or 415 when using json

I have a couple of web services calls using the request package in python one is purely form and WORKS:
r = requests.post('http://localhost:5000/coordinator/finished-crawl', \
data = {'competitorId':value})
And the other uses JSON and does not work:
service_url = 'http://localhost:5000/coordinator/save-page'
data = {'Url': url, 'CompetitorId': competitorID, \
'Fetched': self.generateTimestamp(), 'Html': html}
headers = {'Content-type': 'application/json'}
r = requests.post(service_url, data=json.dumps(data), headers=headers)
Now if do not include headers I use the headers as above, I get a 404, but if I do not include as
r = requests.post(service_url, data=json.dumps(data))
I get a 415. I have tried looking at other post on stackoverflow and from what I can tell the call is correct. I have tested the web service via the application postman and it works. Can some tell me what is wrong or point me in the right direction?
THE FULL METHOD
def saveContent(self, url, competitorID, html):
temp = self.cleanseHtml(html)
service_url = 'http://localhost:5000/coordinator/save-page'
data = {'Url': url, 'CompetitorId': competitorID, \
'Fetched': self.generateTimestamp(), \
'Html': temp}
headers = {'Content-type': 'application/json'}
r = requests.post(service_url, json=json.dumps(data), headers=headers)
r = requests.post(service_url, json=json.dumps(data))
And cleanseHTML:
def cleanseHtml(self, html):
return html.replace("\\", "\\\\")\
.replace("\"", "\\\"")\
.replace("\n", "")\
.replace("\r", "")

Categories