I am using requests.get() to invoke the REST api. When i hardcode the URL it is working fine but if i append the account name with URL getting the response code as 500. Please help.
header = {'Authorization': token_type + " " + token, 'Content-Type': 'application/json'}
account_name="test_account"
uri = "https://my_instance.salesforce.com/services/apexrest/account/entitlement?AccountName="+account_name
user_create_res = requests.get(uri, headers=header)
but same code is working when i give,
header = {'Authorization': token_type + " " + token, 'Content-Type': 'application/json'}
uri = "https://my_instance.salesforce.com/services/apexrest/account/entitlement?AccountName=test_account"
user_create_res = requests.get(uri, headers=header)
Try printing the account_name variable using
print(account_name)
Make sure the text logged in the console is the same as the name you tried hard coding.
Though it could also be that the account_name variable is not a String.
I can not say for sure if I don't get more info like where you define the account_name variable.
Related
request = requests.get(f"https://api.mercadopago.com/v1/payments/{id}")
https://i.stack.imgur.com/Iqrsw.png
Is there a way to do this with requests?
According to this https://www.mercadopago.com.ar/developers/en/reference/payments/_payments_id/get you need to provide a header with your access token you get through OAUTH. And then once you get the access token, you can do
header = {"Authorization": "Bearer " + "your access token"}
result = requests.get(f"https://api.mercadopago.com/v1/payments/{id}", headers=header)
which will return you a json result
I am attempting to make a POST to a web server. I have data that I want to post in the body and headers (taken directly from Chrome). Without going into too many details, when I explicitly set headers, I get a 400 response code.
# Explicitly set headers causes 400 response
req = requests.post(url, auth_form, headers=authenticate)
print(req.status_code)
But the following returns a 200 response code:
# Setting data as my form to post and headers as json
# Returns a 200 response code
req = requests.post(url, auth_form, authenticate)
print(req.status_code)
I am attempting to simulate a login through code. Even when I receive the 200 response I do not successfully login. I suspect this is because I am not properly setting the headers, but I am unsure.
I am actually able to remove the headers entirely (as either headers= or json) and still receive a 200 response code. I believe this reinforces the idea that the headers are not being set properly.
# Removing headers entirely
# Returns a 200 response code
req = requests.post(url, auth_form)
print(req.status_code)
I am not sure if additional details (such as what some of the headers are) will be necessary. If so, I will provide as much of that information as I can.
Edit: Headers, as requested:
authenticate = {}
authenticate["Accept"] = accept
authenticate["Accept-Encoding"] = "gzip, deflate, br"
authenticate["Accept-Language"] = "en-US,en;q=0.8"
authenticate["Cache-Control"] = "max-age=0"
authenticate["Connection"] = "keep-alive"
authenticate["Host"] = dns + ":" + str(port)
authenticate["Origin"] = "http://" + dns + ":" + str(port)
authenticate["Referer"] = "http://" + dns + ":" + str(port) + "/eproc/"
authenticate["Upgrade-Insecure-Requests"] = upgrade_insecure
authenticate["Cookie"] = "ID=" + self.session_id
authenticate["User-Agent"] = user_agent
auth_form = {}
auth_form["username"] = username
auth_form["password"] = password
I am making API requests via Python's 'requests'-module. I am getting the access_token, which is a Bearer token.
I've put the token into a variable like this:
def get_token():
url = 'https://myapiurl.com/oauth/token'
payload = {'username':'myusername', 'password':'mypassword'}
headers = {'Content-Type': 'application/json', 'origin': 'https://blabla.com'}
r = requests.post(url, data=json.dumps(payload),headers=headers)
mytoken = r.json()['token_type']
mytokentype = r.json()['access_token']
token_param = str(mytoken) + ' ' + str(mytokentype)
return token_param
The output is a string that has this structure:
Bearer eyJ0eXAiOiJKV1QiLCJhb.....0sImF6cCI6ImVCOEdI
I need this structure for the following GET requests where this access_token is required. I don't want to get a new token everytime I make a new GET-request.
I have issues in finding out how to:
1: store an access_token
2: check if the access_token is valid
3: use this token to make other GET requests on my API.
I am very thankful for any advice.
My answer:
I've put the whole output of my POST request into the variable result.
The structure of my token has to be like this: "Bearer tokenstring".
So I put the type into the variable result_tokentypeand the token string into the variable result_accesstoken.
Finally I put them together into the variable accessToken:
result_tokentype = result["token_type"]
result_accesstoken = result["access_token"]
accessToken = str(result_tokentype) + " " + str(result_accesstoken)
Now that I have the complete string in the right structure, I can use this variable for the next requests, e.g.:
url = "https://myurl.com"
headers = {"Authorization": accessToken, "key1": "value1", "Content-Type": "application/json" }
conn.request("GET", url, headers=headers)
This worked the best for me, here.
I'm new to getting data using API and Python. I want to pull data from my trading platform. They've provided the following instructions:
http://www.questrade.com/api/documentation/getting-started
I'm ok up to step 4 and have an access token. I need help with step 5. How do I translate this request:
GET /v1/accounts HTTP/1.1
Host: https://api01.iq.questrade.com
Authorization: Bearer C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp
into Python code? I've tried
import requests
r = requests.get('https://api01.iq.questrade.com/v1/accounts', headers={'Authorization': 'access_token myToken'})
I tried that after reading this: python request with authentication (access_token)
Any help would be appreciated. Thanks.
As you point out, after step 4 you should have received an access token as follows:
{
“access_token”: ”C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp”,
“token_type”: ”Bearer”,
“expires_in”: 300,
“refresh_token”: ”aSBe7wAAdx88QTbwut0tiu3SYic3ox8F”,
“api_server”: ”https://api01.iq.questrade.com”
}
To make subsequent API calls, you will need to construct your URI as follows:
uri = [api_server]/v1/[rest_operation]
e.g.
uri = "https://api01.iq.questrade.com/v1/time"
Note: Make sure you use the same [api_server] that you received in your json object from step 4, otherwise your calls will not work with the given access_token
Next, construct your headers as follows:
headers = {'Authorization': [token_type] + ' ' + [access_token]}
e.g.
headers = {'Authorization': 'Bearer C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp'}
Finally, make your requests call as follows
r = requests.get(uri, headers=headers)
response = r.json()
Hope this helps!
Note: You can find a Questrade API Python wrapper on GitHub which handles all of the above for you.
https://github.com/pcinat/QuestradeAPI_PythonWrapper
Improving a bit on Peter's reply (Thank you Peter!)
start by using the token you got from the QT website to obtain an access_token and get an api_server assigned to handle your requests.
# replace XXXXXXXX with the token given to you in your questrade account
import requests
r = requests.get('https://login.questrade.com/oauth2/token?grant_type=refresh_token&refresh_token=XXXXXXXX')
access_token = str(r.json()['access_token'])
refresh_token= str(r.json()['refresh_token']) # you will need this refresh_token to obtain another access_token when it expires
api_server= str(r.json()['api_server'])
token_type= str(r.json()['token_type'])
api_server= str(r.json()['api_server'])
expires_in = str(r.json()['expires_in'])
# uri = api_server+'v1/'+[action] - let's try checking the server's time:
uri = api_server+'v1/'+'time'
headers = {'Authorization': token_type +' '+access_token}
# will look sth like this
# headers will look sth like {'Authorization': 'Bearer ix7rAhcXx83judEVUa8egpK2JqhPD2_z0'}
# uri will look sth like 'https://api05.iq.questrade.com/v1/time'
# you can test now with
r = requests.get(uri, headers=headers)
response = r.json()
print(response)
I am learning Python and I am trying to create a playlist using the Spotify web api but get a http 400 error: Error parsing json. I guess it has to do with an incorrect variable type in the token but I am having a really hard time debugging it as I can't figure out a way to see the post request in raw format.
Posting through the API requires authorizing and this is the script I've created for that:
import requests
import base64
requests.packages.urllib3.disable_warnings()
client_id = 'ID'
client_secret = 'SECRET'
redirect_uri = 'http://spotify.com/'
scope = 'playlist-modify-private playlist-read-private'
def request_token():
# 1. Your application requests authorization
auth_url = 'https://accounts.spotify.com/authorize'
payload = {'client_id': client_id, 'response_type':'code','redirect_uri':redirect_uri}
auth = requests.get(auth_url,params = payload)
print '\nPlease go to this url to authorize ', auth.url
# 2. The user is asked to authorize access within the scopes
# 3. The user is redirected back to your specified URI
resp_url = raw_input('\nThen please copy-paste the url you where redirected to: ')
resp_code= resp_url.split("?code=")[1].split("&")[0]
# 4. Your application requests refresh and access tokens
token_url = 'https://accounts.spotify.com/api/token'
payload = {'redirect_uri': redirect_uri,'code': resp_code, 'grant_type': 'authorization_code','scope':scope}
auth_header = base64.b64encode(client_id + ':' + client_secret)
headers = {'Authorization': 'Basic %s' % auth_header}
req = requests.post(token_url, data=payload, headers=headers, verify=True)
response = req.json()
return response
This is the function actually trying to create the playlist using the authorization token (import authorizer is the function above):
import requests
import authorizer
def create_playlist(username, list_name):
token = authorizer.request_token()
access_token = token['access_token']
auth_header = {'Authorization': 'Bearer {token}'.format(token=access_token), 'Content-Type': 'application/json'}
api_url = 'https://api.spotify.com/v1/users/%s/playlists' % username
payload = {'name': list_name, 'public': 'false'}
r = requests.post(api_url, params=payload, headers=auth_header)
But whatever I try it only leads to a 400 error. Can anyone please point out my error here?
Solved by adding a json.dumps for the input: json.dumps(payload) and changing the payload to be 'data' and not 'params' in the request.
So the new functioning request equals:
r = requests.post(api_url, data=json.dumps(payload), headers=auth_header)