python LinkedIn api connection - python

I am connecting to linkedin api through python.
url = 'https://www.linkedin.com/uas/oauth2/accessToken'
data = [
{'client_id': 'xxx'},
{'client_secret': 'xxx'},
{'grant_type': 'authorization_code'},
{'redirect_uri' : 'xxx'},
{'code': xxx}
]
headers = {'Content-type': 'application/x-www-form-urlencoded'}
r = requests.post(url, data=json.dumps(data), headers=headers)
return HttpResponse(r)
but I am getting the following error :
{"error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : client_id","error":"invalid_request"}
what is the reason for this error ? how to debug ? please help.

That is a strange way to format the data. You have each parameter in a separate dictionary. I guess you want a single dict:
data = {
'client_id': 'xxx',
'client_secret': 'xxx',
'grant_type': 'authorization_code',
'redirect_uri' : 'xxx',
'code': xxx
}
Also, you specify the content type as form-encoded, but you then serialize the actual data as JSON. Don't do that.
r = requests.post(url, data=data, headers=headers)

Related

Pinterst api: not able to get access token - Stuck in Oauth flow

Using v5 of the pinterest api and stuck on the authentication flow: https://developers.pinterest.com/docs/getting-started/authentication/
Completed the first step and got the access code.
However, I get the below error when I try to use this code to get the access token.
{"code":1,"message":"Missing request body"}
Here is my code:
client_id= 'my_client_id'
client_secret = 'my_client_secret'
data_string = f'{client_id}:{client_secret}'
token = base64.b64encode(data_string.encode())
headers = {
'Authorization': 'Basic ' + token.decode('utf-8'),
'Content-Type': 'application/x-www-form-urlencoded',
}
url = "https://api.pinterest.com/v5/oauth/token"
code = "my_code_that_i_got_in_the_first_step"
params = {
'grant_type':'authorization_code',
'code': code,
'redirect_url':'https://my_redirect_uri'
}
r = requests.post(url, headers=headers, params=params)
print(r.json())
Below is the correct way to get the access token:
client_id= 'my_client_id'
client_secret = 'my_client_secret'
data_string = f'{client_id}:{client_secret}'
token = base64.b64encode(data_string.encode())
headers = {
'Authorization': 'Basic ' + token.decode('utf-8'),
'Content-Type': 'application/x-www-form-urlencoded',
}
url = "https://api.pinterest.com/v5/oauth/token"
code = "my_code_that_i_got_in_the_first_step"
data= {
'grant_type':'authorization_code',
'code': code,
'redirect_uri':'https://my_redirect_uri'
}
r = requests.post(url, headers=headers, data=data)
print(r.json())
In my question, I had mistyped redirect_uri as redirect_url. Also, when sending a POST, you should use data instead of params. See the comment by Amos Baker.

python requests not recognizing params

I am requesting to mindbodyapi to get token with the following code using requests library
def get_staff_token(request):
URL = "https://api.mindbodyonline.com/public/v6/usertoken/issue"
payload = {
'Api-Key': API_KEY,
'SiteId': "1111111",
'Username': 'user#xyz.com',
'Password': 'xxxxxxxx',
}
r = requests.post(url=URL, params=payload)
print(r.text)
return HttpResponse('Done')
gives a response as follows
{"Error":{"Message":"Missing API key","Code":"DeniedAccess"}}
But if I request the following way it works, anybody could tell me, what I am doing wrong on the above code.
conn = http.client.HTTPSConnection("api.mindbodyonline.com")
payload = "{\r\n\t\"Username\": \"username\",\r\n\t\"Password\": \"xxxxx\"\r\n}"
headers = {
'Content-Type': "application/json",
'Api-Key': API_KEY,
'SiteId': site_id,
}
conn.request("POST", "/public/v6/usertoken/issue", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
In the second one, you are passing the API Key in headers and the credentials in the body of the request. In the first, you are sending both the API Key and credentials together in the query string, not the request body. Refer to requests.request() docs
Just use two dictionaries like in your second code and the correct keywords, I think it should work:
def get_staff_token(request):
URL = "https://api.mindbodyonline.com/public/v6/usertoken/issue"
payload = {
'Username': 'user#xyz.com',
'Password': 'xxxxxxxx',
}
headers = {
'Content-Type': "application/json",
'Api-Key': API_KEY,
'SiteId': "1111111",
}
r = requests.post(url=URL, data=payload, headers=headers)
print(r.text)
return HttpResponse('Done')

Hubspot API Not Populating Deal

When I'm trying to create a deal through the hubspot api, all that is being created is a completely blank deal even though I am passing through populated data
Api Url: https://developers.hubspot.com/docs/api/crm/deals
Here is the following code that I am trying:
import json
import requests
hubspot_api_key = "MY_API_KEY"
url = 'https://api.hubapi.com/crm/v3/objects/deals?hapikey={}'.format(hubspot_api_key)
headers = {"Content-Type": "application/json"}
deals_post = {
'amount': "4034.75",
'closedate': '2021-05-10T12:04:00.000Z',
'dealname': 'Custom data integrations',
'dealstage': 'closedwon',
'hubspot_owner_id': "5448459615",
'pipeline': 'default'
}
response = requests.post(url, headers=headers, data=json.dumps(deals_post))
print(response.text)
And here is the result of it:
The solution to this issue would be adding properties to the data dictionary
import json
import requests
hubspot_api_key = "MY_API_KEY"
url = 'https://api.hubapi.com/crm/v3/objects/deals?hapikey={}'.format(hubspot_api_key)
headers = {"Content-Type": "application/json"}
deals_post = {
'properties': {
'amount': "4034.75",
'closedate': '2021-05-10T12:04:00.000Z',
'dealname': 'Custom data integrations',
'dealstage': 'closedwon',
'hubspot_owner_id': 83849850,
'pipeline': 'default'
}
}
response = requests.post(url, headers=headers, data=json.dumps(deals_post))
print(response.text)
This results in a filled out deal according to the data that was passed in

Retrieving single json object from python requests results as list

I'm trying to retrieve only requestId object from json results after querying my API.
my code:
def findRequests(group, token, user):
headers = { 'accept': 'application/json',
'Content-Type': 'application/json',
'token': token,
'user': user}
endpoint = 'requests/find'
body = {'groupIDs': [group], "createdDate": {'operator': "BETWEEN", 'fromDate': "01-APR-2020 00:00:00", 'toDate': "21-APR-2020 00:00:00"}}
r = requests.post(url = host + endpoint, headers = headers, json=body, verify=False)
data = json.loads(r.text)
print (data[0]['requestId'])
json data:
[{'requestId': 2567887, 'requestName': 'Here is a sample name', 'requestSubject': 'sample subject', 'createdDate': '01-APR-2020 14:06:03'}, {'requestId': 7665432,...}]
then I would like to save all the values for requestId object found in results as a list:
myRequestsList = print(findRequests(group, token, user))
However the above will only return a single requestId and not all of the ones that were returned in data variable in def findRequests(group, token, user). What am I doing wrong?
Output:
2567887
None
Desired output:
2567887,
7665432
Could someone help me with this? thanks in advance!
First, you should modify your func:
Then, assign the variable to the func, not the print:
myRequestsList = list(findRequests(group, token, user)))
(!) However, I assume that group,token, user are replaced by other variables.
And finally, to get the output:
for req in myRequestsList:
print(req)
Later edit:
def findRequests(group, token, user):
headers = { 'accept': 'application/json',
'Content-Type': 'application/json',
'token': token,
'user': user}
endpoint = 'requests/find'
body = {'groupIDs': [group], "createdDate": {'operator': "BETWEEN", 'fromDate': "01-APR-2020 00:00:00", 'toDate': "21-APR-2020 00:00:00"}}
r = requests.post(url = host + endpoint, headers = headers, json=body, verify=False)
data = json.loads(r.text)
final_list = []
for each_req in data:
final_list.append(each_req['requestId'])
return final_list
myRequestsList = findRequests(group, token, user)
for each in myRequestsList:
print(each)

How to convert http request to Python?

I need your help.
I am looking to communicate with a REST API containing sensor data at port number 3.
I have a Json (POST) request that works perfectly executed on a REST client like Insomnia.
My request :
{ "header": { "portNumber": 3 }, "data": { "index": 40 } }
Picture of my request
However I am unable to make it work on Python and to recover data from my sensor.
My Python code :
import requests
import json
url = 'http://192.168.1.100/iolink/sickv1' # Address of the OctoPrint Server
header = {'portNumber': '3', 'Content-Type': 'application/json'} #Basic request's header
data = {'index': 40}
def get_sensor_measure():
r = requests.post(url + '/readPort', headers=header, data=data)
print(r.content)
print(r.status_code)
I get the error:
b'{"header":{"status":1,"message":"Parsing Failed"}}'
Thank you in advance
You should pass 'portNumber': '3' in data not in header:
header = {'Content-Type': 'application/json'}
data = {'header': {'portNumber': '3'}, 'data': {'index': 40}}
And also as Karl stated in his answer you need to changes data to json:
r = requests.post(url + '/readPort', headers=header, json=data)
My guess would be that you are using the wrong field to pass your payload. It isn't really obvious, but the requests package expects JSON-type payload to be sent with the json field, not the data field, i.e.:
r = requests.post(url + '/readPort', headers=header, json=data)
With a few changes (Bold), it works. Thanks
url = 'http://192.168.1.100/iolink/sickv1' # Address of the OctoPrint Server
header = {'Content-Type': 'application/json'} #Basic request's header
**data = {'header': {'portNumber': 3}, 'data': {'index': 40}}**
def get_sensor_measure():
r = requests.post(url + '/readPort', headers=header, json=data)
print(r.content)
print(r.status_code)

Categories

Resources