I would like to obtain data from a website, in which APIs can be accessed through an authentication request using my username and password. This should then give me a token with which I can download the data I want from the API. But I failed in obtaining the token.
Here is what I tried:
import requests
import json
# URL for the authentication endpoint
auth_url = "https://datadis.es/nikola-auth/tokens/login"
# Replace with your actual username and password
auth_data = {
"username": "username",
"password": "password"
}
# Headers for the request
headers = {
"Content-Type": "application/json",
"Accept": "application/json"
}
try:
# Sending the POST request to the authentication endpoint
response = requests.post(auth_url, data=json.dumps(auth_data), headers=headers)
# Print the response status code and content for debugging
print(f"Response Status Code: {response.status_code}")
print(f"Response Content: {response.text}")
# Check if the request was successful
if response.status_code == 200:
# Parse the JSON response to get the token
response_data = response.json()
token = response_data.get("token")
if token:
print(f"Authentication Token: {token}")
else:
print("Token not found in the response.")
else:
print(f"Failed to obtain token. Status code: {response.status_code}")
print(f"Error message: {response.text}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
Could anyone tell me if I made an error in my code, please?
Error obtained through running above code:
Response Status Code: 500
Thank you very much for your insights, help and time.
All the best,
Ok, I think I succeeded in obtaining the authorization 200.
import requests
import json
# URL for the authentication endpoint
auth_url = "https://datadis.es/michael-auth/tokens/login"
# Replace with your actual username and password
auth_data = {
"username": "username",
"password": "password"
}
When I ran the above code:
200
<Response [200]>
But now, I don’t know how to extract data from it:
Well, from what I’ve read in the docs, .json() returns the same result as the Python’s standard library’s json.loads() which means you get a Python object. In your case it is (probably) a list of dict-s, so you can do anything with them as with any other Python’s object
You can extract API data, it is just that the type of what .json() returns is a standard Python’s object. There is nothing special about it. If you want to do some interpretation of that content, then you have to do it manually.