How to config Bearer Token when making a GET request? - python

Here is the Bearer Token in Postman:
Here is what I do in code:
url_apollo = https://
params_apollo = {
'ID': 123,
}
Here is the requests that I made:
r_apollo = requests.get(url = url_apollo,
params = params_apollo,
headers={'Authorization': 'Bearer ' + 'Token'})
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1
(char 0)

You could do it like this:
url_apollo = https://
params_apollo = {'ID': 123}
headers = {'Authorization': 'Bearer YOURTOKENHERE'}
r_apollo = requests.get(url=url_apollo,
params=params_apollo,
headers=headers)
The reason why you get that error message is within the "params_apollo" variable. Since "ID" is the last line in the JSON, the comma after the value is incorrect and raises a JSONDecodeError.

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.

Trying to retrieve data from the Anbima API

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.

Get bugs from bugzilla using python

I am trying to get bugs to a db from bugzilla rest API. My code is given below.
import requests
import json
URL = "https://bugzilla.mozilla.org/rest/"
API_KEY = "key"
headers = {"Content-type": "application/json"}
params = {
"username": "email",
"password": "password",
"apikey": API_KEY,
}
# r = requests.get(URL + 'login/', headers = headers, params = params)
# print(r)
resp = requests.post(URL + "bug/" , headers = headers, params = params)
if resp.status_code != 200:
print('error: ' + str(resp.status_code))
else:
print('Success')
print(resp)
When I try this I get Response 404.
Someone please direct me to the correct path.
After poking aroung https://resttesttest.com/ I found the answer. Bugzilla API can be authenticate just by API-KEY. So I removed username and password from params dict. It seems I have an error in concatenating the URL too. I just used "https://bugzilla.mozilla.org/rest/bug/35" to get the bug report on bug_id 35. Then json.load(resp.text) gave the json object of the bug report. Final code looks like this.
import requests
import json
URL = "https://bugzilla.mozilla.org/rest/bug/35"
API_KEY = "key"
headers = {"Content-type": "application/json"}
params = {
"api_key": API_KEY,
}
resp = requests.get(URL , headers = headers, params = params)
if resp.status_code != 200:
print('error: ' + str(resp.status_code))
else:
print('Success')
print(json.loads(resp.text))

How to format headers to send with python-requests

I'm not sure how to get the headers in an alphabetical order as the in the example in python-requests. Do the brackets and the punctuation such as ' effect the request headers when they are sent?
This is my code:
headers = {'oauth_callback': "http://www.website-tm-access.co.nz%2Ftrademe-callback",
'oauth_consumer_key' : "5C82CC6BC7C6472154FBC9CAB24A29A2" ,
'oauth_version': "1.0",
'oauth_timestamp': time, #int(time.time()),
'oauth_nonce' : nonce,
'oauth_signature_method' : "HMAC-SHA1",
'oauth_signature' : signature
}
authorization = ', '.join([key + '="' + urllib.parse.quote_plus(str(value)) + '"' for key, value in headers.items()])
http_headers = {'Authorization': authorization}
The Output is:
{'Authorization': 'oauth_nonce="62942100", oauth_callback="http%3A%2F%2Fwww.website-tm-access.co.nz%252Ftrademe-callback", oauth_consumer_key="5C82CC6BC7C6472154FBC9CAB24A29A2", oauth_version="1.0", oauth_timestamp="1457345962", oauth_signature="b%27o0rNPtba78EQ3ALsg2mX1Y4vIQw%3D%27", oauth_signature_method="HMAC-SHA1"'}
The output as defined in the example:
To make the Authorization header, you simply append all the values
starting with “OAuth”. Each value must be URL encoded.
Authorization: OAuth oauth_callback="http%3A%2F%2Fwww.website-tm-access.co.nz%2Ftrademe-callback", oauth_consumer_key="C74CD73FDBE37D29BDD21BAB54BC70E422", oauth_version="1.0", oauth_timestamp="1285532322", oauth_nonce="7O3kEe", oauth_signature_method="HMAC-SHA1", oauth_signature="5s3%2Bel078a5AXGi43FBDyfg5yWY%3D"
The order shouldn't matter when passing the headers to the requests module.
You can just do:
headers = {'oauth_callback': "http://www.website-tm-access.co.nz%2Ftrademe-callback",
'oauth_consumer_key' : "5C82CC6BC7C6472154FBC9CAB24A29A2" ,
'oauth_version': "1.0",
'oauth_timestamp': int(time.time()),
'oauth_nonce' : nonce,
'oauth_signature_method' : "HMAC-SHA1",
'oauth_signature' : signature
}
r = requests.get(url, headers=headers)

Python Requests: Success/Error Not Called

Trying to use python requests. I'm getting a {"code":141,"error":"success/error was not called"} error when I try to save the response I receive from the url into a variable and then post it back to a different url. Any ideas how I can fix this?
payload = { "email" : "jade#gmail.com", "github" : "https://github.com/"}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/r", json = payload, headers = headers)
#Store the token into a variable
token = r.text
payload = { "token" : token}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/getstring", json = payload, headers = headers)
print r.text
You have to use the actual tokens you get back:
Based on the instructions from the main page:
================================
Stage I: Reverse a string
================================
Once you’re registered, it’s time to get started on the challenges.
The first one is straightforward. You’re going to reverse a string.
That is, if the API says “cupcake,” you’re going to send back “ekacpuc.”
POST a JSON dictionary with the key token and your previous token value to this endpoint:
http://challenge.code2040.org/api/getstring
The getstring endpoint will return a string that your code should then reverse, as in the example above.
Once that string is reversed, send it back to us. POST some JSON to:
http://challenge.code2040.org/api/validatestring
Use the key token for your token.
Use the key string for your reversed string.
Part 1 get out token:
payload = { "email" : "jade#gmail.com", "github" : "https://github.com/"}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/register", json = payload, headers = headers)
#Store the token into a variable
token = r.json() # {u'result': u'ZO8FFqVjWp'}
part 2 get the string:
payload = { "token" :token["result"]}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/getstring", json = payload, headers = headers)
jsn = r.json() # {"result":"Wv55g"} # we need to reverse that string
The final part is actually reversing the string you get from our last post:
payload = {"token" :token["result"], "string" :jsn["result"][::-1]} # jsn["result"][::-1]} reverse the string
r = requests.post("http://challenge.code2040.org/api/validatestring", json = payload, headers = headers)
print(r.json())
{u'result': u'PASS: stage1. Enrollment record updated!'} # all good!
You also had an extra r in your address "http://challenge.code2040.org/r" <- should not be there

Categories

Resources