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.
Related
I've been trying (and failing miserably) to use google's urlfetch module (python within app engine's local server) to retrieve a token from paypal. It works as follows using the "requests" module outside of app engine:
url = base + "/v1/oauth2/token"
payload = {
'grant_type': 'client_credentials',
}
auth_encoded = APP_CLIENT_ID + ":" + APP_SECRET
auth_encoded = base64.b64encode(auth_encoded)
##headers = {'Content-Type': 'application/json', 'Authorization': 'Basic ' + auth_encoded}
headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + auth_encoded}
r = requests.post(url,headers=headers,params=payload)
print r.text
... but I get this message when trying the same thing with urlfetch:
{"error":"unsupported_grant_type","error_description":"Grant Type is NULL"}
... here's the code that I'm using:
url = base + "/v1/oauth2/token"
payload = {"grant_type": "client_credentials"}
auth_encoded = APP_CLIENT_ID + ":" + APP_SECRET
auth_encoded = base64.b64encode(auth_encoded)
headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + auth_encoded}
result = urlfetch.fetch(
url=url,
method=urlfetch.POST,
headers=headers,
payload = payload
)
... I've tried everything that I can think of. Should be a simple thing.
This API call is formatted as application/x-www-form-urlencoded , not JSON.
Therefore:
payload = "grant_type=client_credentials"
or
import urllib
payload = urllib.urlencode({"grant_type": "client_credentials"})
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')
I'm trying to automate a process in which i have to download some brazilian fund quotes from Anbima (Brazil regulator). I have been able to work around the first steps to retrieve the access token but i don't know how to use the token in order to make requests. Here is the tutorial website https://developers.anbima.com.br/en/como-acessar-nossas-apis/.
I have tried a lot of thing but all i get from the request is 'Could not find a required APP in the request, identified by HEADER client_id.'
If someone could share some light. Thank you in advance.
import requests
import base64
import json
requests.get("https://api.anbima.com.br/feed/fundos/v1/fundos")
ClientID = '2Xy1ey11****'
ClientSecret = 'faStF1Hc****'
codeString = ClientID + ":" + ClientSecret
codeStringBytes = codeString.encode('ascii')
base64CodeBytes = base64.b64encode(codeStringBytes)
base64CodeString = base64CodeBytes.decode('ascii')
url = "https://api.anbima.com.br/oauth/access-token"
headers = {
'content-type': 'application/json'
,'authorization': f'Basic {base64CodeString}'
}
body = {
"grant_type": "client_credentials"
}
r = requests.post(url=url, data=json.dumps(body), headers=headers, allow_redirects=True)
jsonDict = r.json()
##################
urlFundos = "https://api-sandbox.anbima.com.br/feed/precos-indices/v1/titulos-publicos/mercado-secundario-TPF"
token = jsonDict['access_token']
headers2 = {
'content-type': 'application/json'
,'authorization': f'Bearer {token}'
}
r2 = requests.get(url=urlFundos, headers=headers2)
r2.status_code
r2.text
I was having the same problem, but today I could advance. I believe you need to adjust some parameters in the header.
Follows the piece of code I developed.
from bs4 import BeautifulSoup
import requests
PRODUCTION_URL = 'https://api.anbima.com.br'
SANDBOX_URL = 'https://api-sandbox.anbima.com.br'
API_URL = '/feed/fundos/v1/fundos/'
CODIGO_FUNDO = '594733'
PRODUCTION = False
if PRODUCTION:
URL = PRODUCTION_URL
else:
URL = SANDBOX_URL
URL = URL + API_URL + CODIGO_FUNDO
HEADER = {'access_token': 'your token',
'client_id' : 'your client ID'}
html = requests.get(URL, headers=HEADER).content
soup = BeautifulSoup(html, 'html.parser')
print(soup.prettify())
The sandbox API will return a dummy JSON. To access the production API you will need to request access (I'm trying to do this just now).
url = 'https://api.anbima.com.br/oauth/access-token'
http = 'https://api-sandbox.anbima.com.br/feed/precos-indices/v1/titulos-publicos/pu-intradiario'
client_id = "oLRa*******"
client_secret = "6U2nefG*****"
client_credentials = "oLRa*******:6U2nefG*****"
client_credentials = client_credentials.encode('ascii')
senhabytes = base64.b64encode(client_credentials)
senha = base64.b64decode(senhabytes)
print(senhabytes, senha)
body = {
"grant_type": "client_credentials"
}
headers = {
'content-type': 'application/json',
'Authorization': 'Basic b0xSYTJFSUlOMWR*********************'
}
request = requests.post(url, headers=headers, json=body, allow_redirects=True)
informacoes = request.json()
token = informacoes['access_token']
headers2 = {
"content-type": "application/json",
"client_id": f"{client_id}",
"access_token": f"{token}"
}
titulos = requests.get(http, headers=headers2)
titulos = fundos.json()
I used your code as a model, then I've made some changes. I've printed the encode client_id:client_secret and then I've copied and pasted in the headers.
I've changed the data for json.
access token is dynamically generated with each time and passed to the requests, its throwing invalid token error .
The access token is dynamically passed and bearer, i am not sure the bearer is correct format to send the token in header, Please correct the error
import requests
Access_URL = 'https://host1/uaa/oauth/token'
client_id='ReadUser1'
client_secret='clientsecret1'
grant_type='client_credentials'
BASE_URL='https://host2/hisrian-rest-api/v1/tags?nameMask=*&maxNumber=500'
response = requests.post(Access_URL,
auth=(client_id, client_secret),
data=
{'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret,'content-type': 'application/x-www-form-urlencoded'})
json_response=response.json()
tokenvalue= (json_response['access_token'])
headers={'Content-Type':'application/json',
'Authorization': Bearer {}".format(tokenvalue)}
auth_response = requests.get(BASE_URL, headers=headers)
print(auth_response.json())
import requests
Access_URL = 'https://host1/uaa/oauth/token'
client_id = 'ReadUser1'
client_secret = 'clientsecret1'
grant_type = 'client_credentials'
BASE_URL = 'https://host2/hisrian-rest-api/v1/tags?
nameMask=*&maxNumber=100'
response = requests.post(Access_URL,
auth=(client_id, client_secret),
data={'grant_type': grant_type, 'client_id':
client_id, 'client_secret': client_secret, 'content-type':
'application/x-www-form-urlencoded'})
json_response = response.json()
tokenvalue = (json_response['access_token'])
headers = {'Authorization': 'Bearer ' +
tokenvalue, 'Content-Type': 'application/json'}
auth_response = requests.get(BASE_URL, headers=headers)
print(auth_response.json())
I want to update the title of a pull request and performing the below to achieve it :- (followed this doc https://developer.github.com/v3/pulls/#update-a-pull-request)
data = {"title": "New title"}
url='https://hostname/api/v3/repos/owner/repo/pulls/80'
token = 'my-token'
headers = {'Content-type': 'application/json', 'Accept': 'application/json', 'Authorization': 'token %s' % token}
resp = requests.patch(url, data=json.dumps(data), headers=headers)
print resp.json()
What am I missing ? Please help.
The following worked for me:
import requests
token = "my-token"
url = "https://api.github.com/repos/:owner/:repo/pulls/:number"
payload = {
"title": "New title"
}
r = requests.patch(url, auth=("username", token), json=payload)
print r.json()