I'm fairly new to using web APIs and pulling data and i'm also pretty new with python. My goal is to make a stat-tracker app but I keep getting a 401 when I try and pull the data.
I've printed out the entire url just to make sure I didn't get it wrong. I copied and pasted the API key exactly so that shouldn't be a problem
api_token = 'api key in python file'
api_url_base = 'https://public-api.tracker.gg/v2/apex/standard/'
headers = {'Content-Type' : 'application/json',
'Authorization' : 'Bearer {}'.format(api_token)}
def get_player_profile():
api_url = '{}profile/psn/Daltoosh'.format(api_url_base)
response = requests.get(api_url, headers=headers)
if response.status_code == 200:
return json.loads(response.content.decode('utf-8'))
else:
return response.status_code, api_url
print(get_player_profile())
#player_profile = get_player_profile()
#if player_profile is not None:
# print("Career Stats:")
# for k, v in player_profile['profile/psn/Daltoosh'].items():
# print('{0}:{1}.format(k, v)')
#else:
# print('[!] Data Request Failed [!]')
I expected a status code of 200 but there seems to be a problem authenticating.
I'm not too well versed in the web API that you are using, but I think you might be using the API token incorrectly. I don't think that specific API requires a Bearer token, but instead a separate header called TRN-Api-Key.
So maybe write something like this:
headers = {'Content-Type' : 'application/json', 'TRN-Api-Key' : api_token}
If you look here, you should be able to read up on how to set up authentication.
Related
I'm currently working on an app, one functionality of it being that it can add songs to the user's queue. I'm using the Spotify API for this, and this is my code to do so:
async def request():
...
uri = "spotify:track:5QO79kh1waicV47BqGRL3g" # temporary, can change later on
header = {'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': "{} {}".format(TOKEN_TYPE, ACCESS_TOKEN)}
data = {'uri': uri}
resp = requests.post(url="https://api.spotify.com/v1/me/player/queue", data=data, headers=header)
...
I've tried a lot of things but can't seem to understand why I'm getting Error 400 (Error 400: Required parameter uri missing).
so the Spotify API for the endpoint you're using suggests that the uri parameter required should be passed as part of the url, instead of as a data object.
Instead of data = {'uri': uri} can you please try adding your uri to the end of the url as such:
resp = requests.post(url="https://api.spotify.com/v1/me/player/queue?uri=?uri=spotify%3Atrack%3A5QO79kh1waicV47BqGRL3g", headers=header)
I also suggest using software like postman or insomnia to play around with the requests you send.
I'm trying to import data from CrowdStrike using thier Event-stream API (which I've made sure to enable for the client I use). After authenticating and using the token I get HTTP 401 unauthorized.
client = OAuth2Session(client=BackendApplicationClient(CrowdStrike.get('cid')))
client.fetch_token(token_url=CrowdStrike.get('url_token'), client_secret=CrowdStrike.get('secret'))
response = client.get(CrowdStrike['url_stream']) # 200 OK
# Parse response
j = json.loads(response.text)
url_data_feed = j['resources'][0]['dataFeedURL']
response = client.get(url_data_feed + "&offset=0") # 401 Unauthorized
The last step results an 401 unauthorized- even though the request had an 'Authorization': 'Bearer ' header.
I've even made sure the same bearer is used:
and the token's expired is set to 30 minutes, so it should be vaild.
Any ideas how to fix this?
The following code should work:
resp = requests.get(url_data_feed + "&offset=0",
stream=True,
headers={'Accept': 'application/json',
'Authorization': f'Token {token}'})
This is due to CrowdStrike's authentication requiring the 'Authorization' header to start with 'Token' and not with 'Bearer' (as defaulted by the oauthlib.oauth2 lib).
Also, make sure to include the stream=True as otherwise the program will get stuck.
I have the following python function where im trying to upload a file over to an API that accepts a file as multipart stream. The API correctly works with postman, however im struggling to identify the problem here.
I have parameters (json body) to post to the API along with the file which I have tried to encode inside my mp_encoder variable.
def callAPIwithFile(apiData,apiUrl):
file_ids = ''
jsonData = {'type':apiData['type'],'fromId':apiData['fromid'],'toUserIds':apiData['userIds'],'toGroupIds1':apiData['groupIds'],'toDepartmentIds1':apiData['departmentIds'],'subject':apiData['subject'],'body':apiData['body'],'attachment':apiData['attachment'],'report':apiData['report']}
mp_encoder = MultipartEncoder(fields={'type':apiData['type'],'fromId':apiData['fromid'],'toUserIds':apiData['userIds'],'toGroupIds1':apiData['groupIds'],'toDepartmentIds1':apiData['departmentIds'],'subject':apiData['subject'],'body':apiData['body'],'attachment':apiData['attachment'],'report':apiData['report'],'file': (apiData["attachment"], open(apiData["attachment"], 'rb'), 'application/vnd.ms-excel')})
print mp_encoder
headers = {'Authorization': 'Bearer jwt'}
resp = requests.post(apiUrl,headers=headers,data=mp_encoder)
print resp.text
print "status code " + str(resp.status_code)
if resp.status_code == 201:
print ("Success")
data = json.loads(resp.text)
file_ids = data['file_ids']
print file_ids
else:
print ("Failure")
On running the code I get the following errors :
{"statusCode":400,"message":["type must be a valid alpha, beta, Or gamma","body should not be empty"],"error":"Bad Request"}
status code 400
Failure
As per my understanding the JSON Body that im trying to post to the API is not being recognised correctly. How do I go about this?
Please note, I have tried using request.post(apiUrl,file=files,data=data,header=header) which results in an error of unexpected field.
The below answer could solve my problem :
headers = {'Authorization': 'Bearer '+token}
mydict = dict(type=apiData['type'], fromId=apiData['fromid'], toUserIds1=apiData['userIds'], toGroupIds=apiData['groupIds'], toDepartmentIds1= apiData['departmentIds'], subject= apiData['subject'], body= apiData['body'], attachment= apiData['attachment'], report= apiData['report'])
resp=requests.post(apiUrl, headers = headers, files=dict(attachment=(apiData["attachment"], open(apiData["attachment"], 'rb'), 'application/vnd.ms-excel')),data=mydict)
I am using pandas and requests to create a post request, and the one I am creating sent me back a status code 200 instead of a 201.
In this post, I send a JSON from a dataframe. This part seems to be good.
I don't know if the header is good or not, I changed a lot of things in it, without success.
This problem doesn't show any error and the server affected by the request doesn't give any sign too.
The first request give me the access token and work well.
def post_json(nbr_requests):
auth_json = {'grant_type': 'password', 'client_id': 'hidden','client_secret':'hidden','username':'hidden','password':'hidden'}
auth_response = requests.post('http://hidden:8080/lot/of/stufs/token',data=auth_json)
token = auth_response.json()["access_token"]
api_call_headers = {'content-type':'application/json', 'accept':'application/json','authorization': 'Bearer' + token}
url_to_go = "http://localhost:8080/hidden/link"
for i in range(nbr_requests):
api_call_response = requests.post(url_to_go, headers=api_call_headers, json=json_array_to_send[i],data={"key": "value"})
print (api_call_response.status_code)
I know the question wasn't clear, but if someone got the same problem, you should add a space between "Bearer" and the token in the header.
In my example above you should do something like this :
api_call_headers = {'content-type':'application/json', 'accept':'application/json','authorization': 'Bearer ' + token}
So, I'm new to python and am struggling, self taught, and still learning to code. So be easy on me :)
I am using a script to get data from one source (Jira's API) and trying to use those results to post to another (PowerBi).
I've managed to successfully get the data, I just don't know how to pass the data to this other API.
I know how to use the GET and POST calls, it's just using the data from one to another than I can't seem to find anything about. Assuming since what I'm asking for is very specific?
edit: I also want to mention that while my get is asking for specific data, I'm getting more than I actually need. So I need a way to specify (hopefully) what data is actually being sent to PowerBi's API
import json
import requests
url = 'https://mydomain.atlassian.net/rest/api/2/search'
headers = { 'Content-Type' : 'application/json',
'Authorization' : 'Basic 123456789' }
params = {
'jql' : 'project IN (, PY, CH, NW, RP, DP, KR, DA, RE, SS, CR, CD, AB) AND issueType=incident AND statusCategory!=Done',
'startAt': 0,
'maxResults' : 50,
}
requestget = requests.get(url, headers=headers, params=params)
if requestget.status_code == 200:
print(json.dumps(json.loads(requestget.text), sort_keys=True, indent=4, separators=(",", ": ")))
else:
print("None")
Apologies if I miss understood what you were asking help on, but you could use this to send a POST request as json.
request = urllib.request.Request()#Put the powerbi api here
request.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = #your json data
jsonBytes = jsondata.encode('utf-8')
#Has to be bytes
request.add_header('Content-Length', len(jsonBytes))
response = urllib.request.urlopen(request, jsonBytes)
You could go with a requests.post instead.
jsondata = #put json data here
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(jsondata), headers=headers)
Requests documentation