I am writing a python script which calls the API of Luno.com. It will form part of a larger python script(testing the new API call in a separate script) in which I have already made successful calls to a different site's API, however it did not require authentication. Luno documentation says it needs an API key (which I have) and to use the id and key secret as the username and password in a normal HTTP authentication, being new to python I googled how to do basic HTTP authentication and found this:
from requests.auth import HTTPBasicAuth
result = requests.get('url', auth=('username', 'password'))
I tried using this, but can not seem to get it right no matter what I try,I get the following error when printing the response code and the json output:
<Response [404]>
{'error': 'Cannot find that market', 'error_code': 'ErrMarketNotFound', 'error_action': {}}
I will include my python script and also links to the luno API sections which are applicable. The URL I want to access is https://api.luno.com/api/1/ticker , used to get the currency pair.
https://www.luno.com/en/developers/api
https://www.luno.com/en/developers/api#operation/getTicker
Screenshots if you don't want to click the links:
Python Code:
import json
import requests
from requests.auth import HTTPBasicAuth
urlLuno = 'https://api.luno.com/api/1/ticker'
statsAuthLuno = requests.get(urlLuno, auth=('idhere', 'secretkeyhere'))
print(statsAuthLuno)
print(statsAuthLuno.json())
the ticker API does not require authentication but it does require the market pair as seen here
requests.get(urlLuno, params={"pair": "XBTMYR"})
should get you the details you need.
Or you can get all tickers
Related
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!
I'm trying to learn the requests library in python and I'm following a guide. I'm sending a get request to api.github.com/user but I keep on getting a Status Code of 401. For username, I was using my email at first, but I thought that was what was making it fail so I changed it to my GitHub username and it still doesn't work. Is there anything I'm doing wrong or are there solutions?
import requests
from getpass import getpass
response = requests.get(
"https://api.github.com/user",
auth=('username', getpass())
)
print(response)
You can no longer authenticate to the GitHub API using Basic authentication (a username and password). That ability has been removed. This API endpoint requires authentication because it tells you the current user, and when you're not logged in, there is no current user.
You'll need to generate a personal access token with the appropriate scopes and use it to authenticate to the API instead. You can also use an OAuth token if you're using an OAuth app, but it doesn't sound like you need that in this case.
I am trying to automate the trading strategy that I executed manually before. This requires communicating with my broker through an API. I am authorizing through HTTP basic auth. To test I tried to make an API request to get information about funds in my account.
At first, I was getting 401 responses and it turned out that I was using the wrong identification information.
After I fixed this issue, all API requests that I am making are giving me 404 responses.
An example
import requests
from requests.auth import HTTPBasicAuth
response = requests.get("https://api-demo.exante.eu/md/{version}/accounts", auth=HTTPBasicAuth
('name', 'pass'))
print(response)
After this, I tried some code online to check whether or not there are other problems. I tried this
https://gist.github.com/rshrc/127ba2c20df74263d71bc5a5595c8969
and this also gives me 404.
Link to my brokers API documentation:
https://api-live.exante.eu/api-docs/#section/API-versions
Does anyone know where might be the problem? Directions would be helpful. Thanks!
It looks like you're not passing a version with the {version} variable. Don't forget to also format the URL string with an f before it. This should work:
import requests
from requests.auth import HTTPBasicAuth
version = "3.0"
response = requests.get(f"https://api-demo.exante.eu/md/{version}/accounts", auth=HTTPBasicAuth
('name', 'pass'))
print(response)
I'm trying to do a curl command with python requests. As far as I can tell I'm doing everything correctly but the website won't recognize the api key no matter how I try to include it. Basically, the site I'm trying to reach wants the api key put in the beginning of the url. When I do this with curl, it works perfectly. When I try it via python requests, however, it doesn't work. It also doesn't work to send it in as a key-value pairing in dictionary.
This works
curl -H "Content-Type:application/json" -d '{"ndbno":["11124"],"type":"f"}' [API KEY]#api.nal.usda.gov/ndb/V2/reports
and here's the requests code:
import requests
headers = {'Content-Type': 'application/json',}
data = '{"ndbno":["11124"],"type":"f"}'
response = requests.post('http://[API KEY]#api.nal.usda.gov/ndb/V2/reports', headers=headers, data=data)
The result from this is a json response containing the message: "{'error': {'code': 'API_KEY_MISSING', 'message': 'No api_key was supplied. Get one at http://api.nal.usda.gov:80'}}
"
It also doesn't work if I remove the [API KEY] from the url and add it to the data dictionary as "api_key":"[API KEY]"
BTW I'm not passing the key in as a list or anything, I just didn't want to post the physical key in my question.
I'm a total newb to python and stackoverflow, but I've done my due diligence and have been searching out answers and testing different ways to format the request for a few hours now. Any help is greatly appreciated!
Looking at the PubAG API, it appears that you can simply pass the api_key in the URL query string. I'd assume it's the same for the API you're using, but a cursory search yielded no documentation.
Try:
https://api.nal.usda.gov/ndb/V2/reports?api_key=[API_KEY]
response = requests.post('https://api.nal.usda.gov/ndb/V2/reports?api_key=[API_KEY]', headers=headers, data=data)
I don't have an API key to try this out with, but navigating to https://api.nal.usda.gov/ndb/V2/reports?api_key=asdfds in my browser gives me an invalid API key error, which suggests that the endpoint recognizes that I've given an API key.
It's probably because requests does not parse the API KEY from the URL, try this:
response = requests.post('http://api.nal.usda.gov/ndb/V2/reports', headers=headers, data=data, auth=(API_KEY, ''))
This passes it using Basic Authentication (Authorization header) which is the same behavior that curl does when parsing the URL.
Normally in Basic Auth you would have the username and the password. E.g:
auth=('<username>', '<password>')
Since this API only seems to care about the username, I have left the password as blank.
I have access to an API that I'm trying to start leveraging to automate some tasks and I jumped right into it but was stymied by JWT, which I have never used. I'm also coming off a couple years not using python, so I'm a little rusty. Please bear with me.
Here is a direct quote from the API documentation:
The authentication mode for an organization is with a JSON Web Token. Users
must pass a JSON Web Token (JWT) in the header of each API request made.
To obtain the JWT, send the user’s API key (UUID) and password in a JSON Web
Token GET Request. The authorization method of “Bearer” and a
space is then prefixed to the encoded token string returned. The token will
be tied to the user account that generated the JWT.
I've tried with requests but I'm get 405 errors, I've also installed and imported pyjwt but it's confusing to me. This is essentially what I'm trying to send via python:
POST https://<our endpoint>/v1/token/get HTTP/1.1
Content-Type: application/json
{
"username": "<myUsername>",
"password": "<myPassword>"
I've verified that the target API is working, as there is a small set of functionality that works without JWT and was easily accessed via requests
Advice is welcome, as are any tutorials. I've tried to read several JWT tutorials but I'm having a hard time translating it to python.
Thanks!
Question: To obtain the JWT, send the user’s API key (UUID) and password in a JSON Web Token GET Request
Solution using python_jwt.
Assumptions:
Encoding Method = HS256
claims Fieldname 'consumerId'
claims Fieldname 'httpMethod'
Your JWT in the url looks like:
'http://httpbin.org/get?eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9... (omitted for brevity)
response.json() contains the requested JWT you have to use afterwards.
Note: Your have to use https://<base url>/v1/token/get
import python_jwt as jwt
# Create claims dictionary for generation of JwToken
claims = {
'consumerId': 'My App ID',
'httpMethod': 'GET'
}
import datetime
# create JWToken
jwtoken = jwt.generate_jwt(claims, 'My secret', 'HS256', datetime.timedelta(minutes=5))
response = requests.get('http://httpbin.org/get', jwtoken)
print(response.json())
Tested with Python:3.4.2 - requests:2.11.1