I'm new to a lot of API work and I'm currently working with getting a bearer token from an API. After doing the proper POST request I'm able to get it but I'm getting it in a format that I'd rather not have to work around. I just get a big string of JSON data.
import requests
import os
import webbrowser
CLIENT_ID = [Client_ID]
CLIENT_SECRET = [Client_SECRET]
REDIRECT_URI = [REDIRECT_URI]
RESPONSE_TYPE = [RESPONSE_TPYE]
params = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"redirect_uri": REDIRECT_URI,
"response_type": RESPONSE_TYPE
}
endpoint = [this is the url endpoint]
webbrowser.open(endpoint)
code = input("Enter the Code: ")
print(code)
endpoint2 = "[endpoint without the code]" code
token_endpoint = requests.post(endpoint2)
print(token_endpoint.text)
When executing this code and going through the steps I'm left with this:
{"access_token":"[bearer token here}","token_type":"Bearer","expires_in":7200,"refresh_token":"-[refresh token here]","scope":"read","created_at":[time created at]}
This is a full string object since I'm passing it as "text." I can't get anything to print if I don't do that but I'm willing to change that to get the access_token object to be it's own variable that I can work with.
Any tips are appreciated. Thanks. (note: sensitive information is just put into brackets)
CodePudding user response:
You can use token_endpoint.json()
to get a dictionary instead of text, and then select whichever key-value you want.
If you ever get stuck on anything request
based, your first stop should be their excellent documentation here, most of the times that would answer the question you had. Case in point, here is the section relevant to your question
CodePudding user response:
I've never needed to use webbrowser. I think response = requests.post(url, data=payload_dict)
and json_response.json()
will provide everything you need (cf. requests documentation).
For extracting specific elements via xpath this answer might be helpful: parse html response