How to collect request header data - python

I'm trying to collect this specific data but it gives the error:
print (resp["authorization"])
KeyError: 'authorization'
Code:
https://i.stack.imgur.com/jnxbi.png
What I would like to collect:
https://i.stack.imgur.com/uPwum.png
What should I do to be able to collect this data?

The authorization parameter seems to be in the request header. But, you're trying to find it in the response header where it is unavailable. So when you are trying to access the data using the authorization parameter from the dictionary it returns KeyError
To see the headers you've sent, try the following:
from requests import get
res = get("https://discord.com/api/v8/applications/detectable")
print(res.request.headers)
And please try to always post the code and error message in text, not as screenshots like these.

Related

Python Post Request Issue, given error 500

body_1 = {"landowner": "asdf#gmail.com","title": report_name,"content": "asdf","project": projectID, }
url_1 = 'http://' + IP + ':8005/projects/notifications/'
response_1 = requests.post(url_1, data=body_1, headers=headers)
For this, I am getting an error 500, when above I have used a similar process to post and it has worked.
I even wrote this code in javascript, and that works but the python equivalent does not.
I tried to add console logs, and everything works up until the response, where it says code 500.
I tried to follow along with javascript as well and try and model it after that too, but that did not work either.
You are getting the error because you are not sending the data as JSON encoded data. When sending an array as data with a request use the json keyword argument. This means your request will look like;
response_1 = requests.post(url_1, json=body_1, headers=headers)
In the example above data= was changed to json=.
By using the json argument the data is encoded to JSON, and the Content-Type header is set to application/json.
Learn more about the json= keyword argument in the requests documentation
If this doesn't fix your issue please add the error output message for the 500 error code.

Thoughtspot: API calls to fetch metadata via Python

I'm trying to fetch metadata from thoughtspot. I am able to call the url using browser and fetch the data. But here I'm trying to achieve it via python program. According to thougthspot documentation. I have to enable trusted authentication and pass my secret key & username to obtain a token which I can use in my program.
https://developers.thoughtspot.com/docs/?pageid=api-auth-session
my username : username#username.com
secret key : secret-key
Below is my code:(generated by postman)
import requests
url = "https://<ThoughtSpot-host>/callosum/v1/tspublic/v1/session/auth/token?auth_token=secret-key&access_level=FULL&username=username#username.com"
payload={}
headers = {}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
I'm getting Bad request error. Anyone here using thoughtspot over this issue. Appreciate your support very much.
Error I'm getting:
{"type":"Bad Request","description":"The server could not understand the request due to invalid syntax."}
I can fetch data by calling the api using a web-browser. Below url returns list of all meta-data objects. I want to achieve this using a python program (I have to authenticate first & call the below URL - Authentication step is not working for me when I tried to follow the documentation)
https://<ThoughtSpot-host>/callosum/v1/tspublic/v1/metadata/list
Did you try changing the url so that it includes the domain name?
Also post the error you are getting. And a screenshot of a working request would be great!

bad key error occurred when tried to fetch data from api endpoint in python?

I tried to fetch data from api endpoint using request, but I got a bad key error. In my case, I provided api-key and endpoint url, so I used request to get json content of the data then used pandas to create data frame. I looked into SO but didn't find a clue how to get over this. Does anyone have possible thoughts or attempts to fix this? How can I correctly fetch data from api endpoint? Any idea?
my attempt
I tried to fetch data from this site: market data
import requests
import pandas as pd
api_key = 'ec95a478-e46e-47f9-b57d-3d19012d527d'
url = 'https://apps.fas.usda.gov/OpenData/api/esr/countries'
headers = {'Ocp-Apim-Subscription-Key': '{key}'.format(key=api_key)}
jsonData = requests.get(url, headers=headers).json()
df = pd.read_json(json.dumps(jsonData)
but I got this error after running the above codes:
'Bad API Key'
I accessed to this api and got this instruction as follow:
Hello Adam, your custom API key is
********---****-3d19012d527d Show Please copy and paste your API key into api_key text box in Swagger window below and start
exploring the API. Please ues your custom key as name value pair
API_KEY:Value in HTTP Header, when making API request from your
applications.
where am I wrong in my above attempt? How can I correctly fetch data from any API endpoint on this site? Can anyone suggest a possible way of fetching data from api endpoints with json, request, and pandas? Any thoughts?
You're sending 1 header with your request. That header is named Ocp-Apim-Subscription-Key. Judging by the sliver of email you shared they expect the header to contain a pair named API_KEY.
If that is the issue the following should resolve it.
headers = {'API_KEY': '{key}'.format(key=api_key)}
Formatting a string to be the value of a string variable is redundant. Your code could be cleaned up by removing the call to format()
headers = {'API_KEY': api_key}
One thing to keep in mind
You posted your API key on a public site. Given that API keys are used for authentication, it would be best practice to de-authenticate your current key and request a new one, to prevent unauthorized use.

403 (Forbidden) error when using Fortnite Tracker api with urllib.request

I am attempting to get user statistics from the Fortnite tracker api.
I have an api key and am using the correct url as indicated in the documentation
Template url:
https://api.fortnitetracker.com/v1/profile/{platform}/{epic-nickname}
Desired url:
https://api.fortnitetracker.com/v1/profile/pc/xantium0
If I use this link in browser I get {"message":"No API key found in request"} (as I have not passed the API key) so the link should be correct. Also if I do not pass the api key with urllib then I still get a 403 error.
I have checked out how to pass a header in a request: How do I set headers using python's urllib?
and so far have this code:
import urllib.request as ur
request = ur.Request('https://api.fortnitetracker.com/v1/profile/pc/xantium0', headers={'TRN-Api-Key' : 'xxx'})
response = ur.urlopen(request)
print(response.read())
When run I get this error:
urllib.error.HTTPError: HTTP Error 403: Forbidden
403 checks out as:
HTTP 403 is a standard HTTP status code communicated to clients by an HTTP server to indicate that the server understood the request, but will not fulfill it. There are a number of sub-status error codes that provide a more specific reason for responding with the 403 status code.
https://en.wikipedia.org/wiki/HTTP_403
The response is the same if I don't pass the api key in the header.
I can only think of three reasons this code is not working:
I have passed the wrong header name (i.e. it's not TRN-Api-Key)
My code is incorrect and I am not actually passing a header to the server
I have been banned
My problem is that I think my code is correct:
From the documentation:
urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
I have passed the url and I have passed the headers (wihout confusing with the data arguement). The api documentation also mentions it should be passed in the headers.
I am also quite sure I need to use the TRN-Api-Key as it is shown in the api documentation:
TRN-Api-Key: xxx
Also in this question (using Ruby):
header = {
key: "TRN-Api-Key: Somelong-api-key-here"
}
Or I have been banned (this is possible although I got the key 15 minutes ago) is there a way to check? Would this error be returned?
What is preventing me from getting the user statistics?
Try using requests, a pythonic, fast and widely used module.
import requests
url = 'https://api.fortnitetracker.com/v1/profile/pc/xantium0'
headers = {
'TRN-Api-Key' : 'xxx'
}
response = requests(url, headers=headers)
print('Requests was successful:', response.ok)
print(response.text)
If it doesn't work you can visit the url with your browser, then check the requests:
in Firefox press Cntrl+Shift+E, in Chrome Cntrl+E (or Inspect with Cntrl+Shift+I and then go to Network). Press on "https://api.fortnitetracker.com/v1/profile/pc/xantium0" and change the headers. On Firefox there's the button Modify and resend. Check the response and eventually, try to change the header api key name.
Hope this helps, let me know.

Get all comments help, API returns a 403 error

These are the headers I send with my get request to https://oauth.reddit.com/api/morechildren in python, however I get hit with a 403 error each time I try it. In the #code it seems like either the link is incorrect or that I'm not 'allowed' to see it.
('User-Agent', 'python:xxxxx:xxxxx by (by /u/XXXXXXXXXXXX)')
('Authorization', 'bearer <TOKEN>')
('children', <comma seperated list of ID36s for comments>)
('link_id', 't3_<ID36>')
('sort', 'confidence')
('api_type', 'json')
You need to send the parameters in POST form values rather than JSON. Here's some examples.

Categories

Resources