How To Submit GET Request using urllib-3 in python - python

I'm trying to submit a get request using the following code in AWS Lambda.
hed = {'Authorization': f"bearer {token}"}
URL = "https://integrate.elluciancloud.com/api/academic-periods"
r = http.request('GET', URL, headers=hed)
print(r.data)
The Token which I'm passing is : iLCJ0b2ciOlsiRVhDSEFOR0VfREV.TSUdORVJfRU5BQkxFRCIsIlBBQ0tBR0VTX0ZFQVRVUkVTX0VOQUJMRUQiXSwicm9sZXMiOlsiYWZlZWYyMDQtZTM3MS00MTlhLWE4OTAtOTNlNjYyMWE0MjM4Il0sInRlbmFudCI6eyJpZCI6IjcyMjJhZmEwLWYzNGYtNDRhNy1hZWVmLTEzZDE5NWJkNTQ4YSIsImFjY291bnRJZCI6IkludGVybmFsRWxsdWNpYW5CYW5uZXJNb2Rlcm5pemF
But I'm the following error message in r.data
b'{"errors":[{"code":"General.error","description":"Application error","message":"java.lang.IllegalArgumentException"}]}'
I tried to encode the token (token = token.encode('ascii', 'ignore')) but it's not working

Related

interacting with discord slash commands using requests python

I've automating message sending in discord with a simple script in python
def sendMsg(token:str, channel:str, message:str):
url = 'https://discord.com/api/v9/channels/' + channel + '/messages'
data = {"content": message}
header = {"authorization": token}
r = requests.post(url, data=data, headers=header)
print(r.status_code)
but I want to automate also sending slash commands and there is were i get the error, i've tryed using the url url = 'https://discord.com/api/v9/interactions' maybe the error is in the url that need a channel id but looking with dev tools in the headers: Request URL: https://discord.com/api/v9/interactions the json im going to send gives some errors like true is undefined did you mean True same as null is undefined, i've just doble quoted that, do you know what is the error? the status code is always 400
full code:
import requests
import json
token = 'thIsIsMySecreTt0k3n'
channelId = '1015655803383988314'
with open('data_json.json','r') as f:
s = f.read()
print(s)
dta = s
f.close()
def sendMsg(token:str, channel:str, message:str):
url = 'https://discord.com/api/v9/channels/' + channel + '/messages'
data = {"content": message}
#data = dta
header = {"authorization": token}
r = requests.post(url, data=data, headers=header)
print(r.status_code)
def sendRank(token:str,channel:str):
url = 'https://discord.com/api/v9/interactions'
data = dta
header = {"authorization": token}
r = requests.post(url, data=data, headers=header)
print(r.status_code)
print(type(eval(dta)))
sendRank(token, channelId)
you may also need to see the data_json.json that try to send /rank to probot
{"type":2,"application_id":"282859044593598464","guild_id":"1003270895185436803","channel_id":"1003270896359845998","session_id":"0eaab6fb154d359c5665ca016f1eec11","data":{"version":"971443831096635452","id":"971443830870126634","name":"rank","type":1,"options":[],"application_command":{"id":"971443830870126634","application_id":"282859044593598464","version":"971443831096635452","default_permission":"true","default_member_permissions":"null","type":1,"name":"rank","description":"View your rank card or someone else's in the server.","dm_permission":"true","options":[{"type":6,"name":"user","description":"User to get rank of."}]}}}
or the raw json without beeing modified
{"type":2,"application_id":"282859044593598464","guild_id":"1003270895185436803","channel_id":"1015655803383988314","session_id":"0eaab6fb154d359c5665ca016f1eec11","data":{"version":"971443831096635452","id":"971443830870126634","name":"rank","type":1,"options":[],"application_command":{"id":"971443830870126634","application_id":"282859044593598464","version":"971443831096635452","default_permission":true,"default_member_permissions":null,"type":1,"name":"rank","description":"View your rank card or someone else's in the server.","dm_permission":true,"options":[{"type":6,"name":"user","description":"User to get rank of."}]},"attachments":[]},"nonce":"1015670347103469568"}
Change data=data to json=data, you should get a 204 response code which means it worked.
You also do not need all of that data, the only ones you need are below
{"type":2,"application_id":"","guild_id":"","channel_id":"","session_id":"","data":{"version":"","id":"","name":""}}
Session id does not have to be a vaild id, it just has to be a string that isn't empty.

how to do a python request get command with bearertoken?

I am trying to do a python request get command using python. I have:
endpoint = https://eventsapi.uatxyzreports.com/api/v1/Events/OR/12345
headers = {"Authorization":"abcxyz12345"}
response = requests.get(endpoint, headers = headers)
the response code is ("401")
but when I put in the same token I got a response code of 200. Where did it go wrong?

401 with a POST using requests

Using Postman, I can make a POST to an endpoint with a JSON body, and it returns be some results.
No authorisation on the endpoint.
Trying to get this to work with requests fails with a 401.
What am I missing here:
Code:
import json
import requests
url = 'https://wabi-australia-southeast-api.analysis.windows.net/public/reports/querydata?synchronous=true'
header = {"content-type": "application/json"}
body = {"version":"1.0.0","queries":[{"Query":{"Commands":[{"SemanticQueryDataShapeCommand":{"Query":{"Version":2,"From":[{"Name":"d1","Entity":"dimLGA","Type":0},{"Name":"l","Entity":"Linelist","Type":0}],"Select":[{"Column":{"Expression":{"SourceRef":{"Source":"d1"}},"Property":"LGAName"},"Name":"dimLGA.LGAName"},{"Measure":{"Expression":{"SourceRef":{"Source":"l"}},"Property":"Cases"},"Name":"Linelist.Cases"}],"Where":[{"Condition":{"Not":{"Expression":{"Comparison":{"ComparisonKind":0,"Left":{"Column":{"Expression":{"SourceRef":{"Source":"d1"}},"Property":"LGAName"}},"Right":{"Literal":{"Value":"null"}}}}}}},{"Condition":{"In":{"Expressions":[{"Column":{"Expression":{"SourceRef":{"Source":"l"}},"Property":"clin_status_n"}}],"Values":[[{"Literal":{"Value":"'Admitted to ICU'"}}],[{"Literal":{"Value":"'Admitted, not known to be in ICU'"}}],[{"Literal":{"Value":"'Home isolation'"}}],[{"Literal":{"Value":"'Hotel detention'"}}],[{"Literal":{"Value":"'Hospital in the home'"}}],[{"Literal":{"Value":"'Under investigation'"}}]]}}}]},"Binding":{"Primary":{"Groupings":[{"Projections":[0,1]}]},"DataReduction":{"DataVolume":3,"Primary":{"Window":{"Count":500}}},"Version":1}}}]},"CacheKey":"{\"Commands\":[{\"SemanticQueryDataShapeCommand\":{\"Query\":{\"Version\":2,\"From\":[{\"Name\":\"d1\",\"Entity\":\"dimLGA\",\"Type\":0},{\"Name\":\"l\",\"Entity\":\"Linelist\",\"Type\":0}],\"Select\":[{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"d1\"}},\"Property\":\"LGAName\"},\"Name\":\"dimLGA.LGAName\"},{\"Measure\":{\"Expression\":{\"SourceRef\":{\"Source\":\"l\"}},\"Property\":\"Cases\"},\"Name\":\"Linelist.Cases\"}],\"Where\":[{\"Condition\":{\"Not\":{\"Expression\":{\"Comparison\":{\"ComparisonKind\":0,\"Left\":{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"d1\"}},\"Property\":\"LGAName\"}},\"Right\":{\"Literal\":{\"Value\":\"null\"}}}}}}},{\"Condition\":{\"In\":{\"Expressions\":[{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"l\"}},\"Property\":\"clin_status_n\"}}],\"Values\":[[{\"Literal\":{\"Value\":\"'Admitted to ICU'\"}}],[{\"Literal\":{\"Value\":\"'Admitted, not known to be in ICU'\"}}],[{\"Literal\":{\"Value\":\"'Home isolation'\"}}],[{\"Literal\":{\"Value\":\"'Hotel detention'\"}}],[{\"Literal\":{\"Value\":\"'Hospital in the home'\"}}],[{\"Literal\":{\"Value\":\"'Under investigation'\"}}]]}}}]},\"Binding\":{\"Primary\":{\"Groupings\":[{\"Projections\":[0,1]}]},\"DataReduction\":{\"DataVolume\":3,\"Primary\":{\"Window\":{\"Count\":500}}},\"Version\":1}}}]}","QueryId":"","ApplicationContext":{"DatasetId":"5b547437-24c9-4b22-92de-900b3b3f4785","Sources":[{"ReportId":"964ef513-8ff4-407c-8068-ade1e7f64ca5"}]}}],"cancelQueries":[],"modelId":1959902}
r = requests.post(url, data=json.dumps(body), headers=header)
print(r.status_code)
print(r.raise_for_status())
This returns a 401:
HTTPError: 401 Client Error: Unauthorized for url:
https://wabi-australia-southeast-api.analysis.windows.net/public/reports/querydata?synchronous=true
Just found out Postman lets you generate a python code snippet for Requests. Amazing.
This solved my problem.
import requests
url = "https://wabi-australia-southeast-api.analysis.windows.net/public/reports/querydata"
payload = "{\"version\":\"1.0.0\",\"queries\":[{\"Query\":{\"Commands\":[{\"SemanticQueryDataShapeCommand\":{\"Query\":{\"Version\":2,\"From\":[{\"Name\":\"d1\",\"Entity\":\"dimLGA\",\"Type\":0},{\"Name\":\"l\",\"Entity\":\"Linelist\",\"Type\":0}],\"Select\":[{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"d1\"}},\"Property\":\"LGAName\"},\"Name\":\"dimLGA.LGAName\"},{\"Measure\":{\"Expression\":{\"SourceRef\":{\"Source\":\"l\"}},\"Property\":\"Cases\"},\"Name\":\"Linelist.Cases\"}],\"Where\":[{\"Condition\":{\"Not\":{\"Expression\":{\"Comparison\":{\"ComparisonKind\":0,\"Left\":{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"d1\"}},\"Property\":\"LGAName\"}},\"Right\":{\"Literal\":{\"Value\":\"null\"}}}}}}},{\"Condition\":{\"In\":{\"Expressions\":[{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"l\"}},\"Property\":\"clin_status_n\"}}],\"Values\":[[{\"Literal\":{\"Value\":\"'Admitted to ICU'\"}}],[{\"Literal\":{\"Value\":\"'Admitted, not known to be in ICU'\"}}],[{\"Literal\":{\"Value\":\"'Home isolation'\"}}],[{\"Literal\":{\"Value\":\"'Hotel detention'\"}}],[{\"Literal\":{\"Value\":\"'Hospital in the home'\"}}],[{\"Literal\":{\"Value\":\"'Under investigation'\"}}]]}}}]},\"Binding\":{\"Primary\":{\"Groupings\":[{\"Projections\":[0,1]}]},\"DataReduction\":{\"DataVolume\":3,\"Primary\":{\"Window\":{\"Count\":500}}},\"Version\":1}}}]},\"CacheKey\":\"{\\\"Commands\\\":[{\\\"SemanticQueryDataShapeCommand\\\":{\\\"Query\\\":{\\\"Version\\\":2,\\\"From\\\":[{\\\"Name\\\":\\\"d1\\\",\\\"Entity\\\":\\\"dimLGA\\\",\\\"Type\\\":0},{\\\"Name\\\":\\\"l\\\",\\\"Entity\\\":\\\"Linelist\\\",\\\"Type\\\":0}],\\\"Select\\\":[{\\\"Column\\\":{\\\"Expression\\\":{\\\"SourceRef\\\":{\\\"Source\\\":\\\"d1\\\"}},\\\"Property\\\":\\\"LGAName\\\"},\\\"Name\\\":\\\"dimLGA.LGAName\\\"},{\\\"Measure\\\":{\\\"Expression\\\":{\\\"SourceRef\\\":{\\\"Source\\\":\\\"l\\\"}},\\\"Property\\\":\\\"Cases\\\"},\\\"Name\\\":\\\"Linelist.Cases\\\"}],\\\"Where\\\":[{\\\"Condition\\\":{\\\"Not\\\":{\\\"Expression\\\":{\\\"Comparison\\\":{\\\"ComparisonKind\\\":0,\\\"Left\\\":{\\\"Column\\\":{\\\"Expression\\\":{\\\"SourceRef\\\":{\\\"Source\\\":\\\"d1\\\"}},\\\"Property\\\":\\\"LGAName\\\"}},\\\"Right\\\":{\\\"Literal\\\":{\\\"Value\\\":\\\"null\\\"}}}}}}},{\\\"Condition\\\":{\\\"In\\\":{\\\"Expressions\\\":[{\\\"Column\\\":{\\\"Expression\\\":{\\\"SourceRef\\\":{\\\"Source\\\":\\\"l\\\"}},\\\"Property\\\":\\\"clin_status_n\\\"}}],\\\"Values\\\":[[{\\\"Literal\\\":{\\\"Value\\\":\\\"'Admitted to ICU'\\\"}}],[{\\\"Literal\\\":{\\\"Value\\\":\\\"'Admitted, not known to be in ICU'\\\"}}],[{\\\"Literal\\\":{\\\"Value\\\":\\\"'Home isolation'\\\"}}],[{\\\"Literal\\\":{\\\"Value\\\":\\\"'Hotel detention'\\\"}}],[{\\\"Literal\\\":{\\\"Value\\\":\\\"'Hospital in the home'\\\"}}],[{\\\"Literal\\\":{\\\"Value\\\":\\\"'Under investigation'\\\"}}]]}}}]},\\\"Binding\\\":{\\\"Primary\\\":{\\\"Groupings\\\":[{\\\"Projections\\\":[0,1]}]},\\\"DataReduction\\\":{\\\"DataVolume\\\":3,\\\"Primary\\\":{\\\"Window\\\":{\\\"Count\\\":500}}},\\\"Version\\\":1}}}]}\",\"QueryId\":\"\",\"ApplicationContext\":{\"DatasetId\":\"5b547437-24c9-4b22-92de-900b3b3f4785\",\"Sources\":[{\"ReportId\":\"964ef513-8ff4-407c-8068-ade1e7f64ca5\"}]}}],\"cancelQueries\":[],\"modelId\":1959902}"
headers = {
'Content-Type': 'text/plain'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))

Python put request. Spotify API put request Malformed Json

I would really appreciate some help here. I am trying to use the Spotify API to add albums to a users library. I have been struggling with a Malformed Json Payload, and am completely out of ideas.
Here is a simplified version of what I am currently sitting on
url = 'https://api.spotify.com/v1/me/albums'
payload = {'body': ['01kTgTBiZkCFY3ZH2hBH6u', '4sz6Fn4BYORRLIc1AvQwQx']}
headers = {'Authorization':'Bearer {}'.format(access_token), 'Content-Type':'application/json',}
response = requests.put(url,headers=headers, data=payload)
print(response.json())
The error I am receiving is in the json response:
{'error': {'status': 400, 'message': 'Malformed json payload'}}
I have tried changing requests.put as per below, but all attempts are returning the same error
response = requests.put(url,headers=headers, json=payload)
response = requests.put(url,headers=headers, data=json.dumps(payload))
response = requests.put(url,headers=headers, json=json.dumps(payload))
07bYtmE3bPsLB6ZbmmFi8d: This spotify id is for the album, Dancefloor Hits #1. I checked my spotify acct and there it was in my Albums on my acct. Below is my code to run that.
import requests
url = "https://api.spotify.com/v1/me/albums"
payload = {"ids": "27cZdqrQiKt3IT00338dws"}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer %s' % (access_token) # paste your access token in here
}
''' you can use the same syntax as above but the key was that your ID of album had to be a **parameter** not ***data***.
To do that you use the params kwarg'''
response = requests.request("PUT", url, headers=headers, params = payload)
print(response.status_code) # should print out 200 when you run the code
# shows whether status was valid

Receiving a JSON response from a POST request

Using a POST request, my goal is to receive an authorization code from a JSON response. However, the only response I'm getting is the HTML of the webpage I'm connecting to, not the desired JSON response.
import requests
from base64 import b64encode
appAuth = b64encode(b"QT8txxxxxxxx:n76mxxxxxxxxx").decode("ascii")
headers = { 'Authorization' : 'Basic %s' % appAuth }
url = "http://demo.skubana.com?grant_type=authorization_code&redirect_uri=demo.skubana.com/appstore&code=LCqYHU&cid=Y29tcGFueUlkMTI0MDYw"
r = requests.post(url, headers=headers,json={})
print(r.status_code)
print(r.content)
The supplied API documentation for Skubana is, in my opinion, shockingly under-specified.
What you may have missed is this part:
Add the request path: /oauth/token
which, to be fair, is not reflected in their 'sample URL':
Sample Url: https://blah.skubana.com?grant_type=authorization_code&redirect_uri=redirect.com/callback&code=ABCDE&cid=ABCD1234
When you change your URL to include that path, I get a 401 Unauthorized response instead:
>>> url = "http://demo.skubana.com/oauth/token?grant_type=authorization_code&redirect_uri=demo.skubana.com/appstore&code=LCqYHU&cid=Y29tcGFueUlkMTI0MDYw"
>>> r = requests.post(url, headers=headers)
>>> r.status_code
401
This too, incidentally, also involves a redirect from POST to GET. But I strongly suspect that with the right credentials (which I don't have) you'd actually get your token.
When you post to https://demo.skubana.com, you are redirected, first to the same URL to make a GET request, with:
Location: https://demo.skubana.com/?grant_type=authorization_code&redirect_uri=demo.skubana.com/appstore&code=LCqYHU&cid=Y29tcGFueUlkMTI0MDYw
then on to your dashboard:
Location: /work/dashboard
and finally to the login page:
Location: https://demo.skubana.com/login
All this is recorded in the r.history list:
>>> r.history
[<Response [302]>, <Response [302]>, <Response [302]>]
Note that you don't have to set json={}, just use:
r = requests.post(url, headers=headers)
The requests library can take care of the Base64 encoding for you as that's just part of the Basic Authentication scheme, just pass in the YOUR_APP_KEY and YOUR_APP_SECRET values as username and password:
YOUR_APP_KEY = "QT8txxxxxxxx"
YOUR_APP_SECRET = "n76mxxxxxxxxx"
url = "http://demo.skubana.com/oauth/token"
parameters = {
"grant_type": "authorization_code",
"redirect_uri": "demo.skubana.com/appstore",
"code": "LCqYHU",
"cid": "Y29tcGFueUlkMTI0MDYw",
}
r = requests.post(url, params=parameters, auth=(YOUR_APP_KEY, YOUR_APP_SECRET))
Finally, given the redirect and complete lack of POST parameters, I strongly suspect that a GET request works just as well:
r = requests.get(url, params=parameters, auth=(YOUR_APP_KEY, YOUR_APP_SECRET))
This just bypasses the POST -> GET redirect.
Normally, a OAuth2 request for a token like this would post the parameters in the POST body, so do also try:
r = requests.post(url, data=parameters, auth=(YOUR_APP_KEY, YOUR_APP_SECRET))
if the params=parameters options don't get you your token, still.

Categories