Obtain API data token using -requests-

Hi Python Community,

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,

Michael

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:

Basically, I want data from: https://datadis.es/api-public/api-sum-search
The parameters are the following:

  1. startDate - string($date-time) required
  2. endDate - string(date-time) required
  3. measurementType - array[string]
  4. community - array[string] required
  5. distributor - array[string]
  6. fare - array[string]
  7. provinceMunicipality - array[string]
  8. postalCode array[string]
  9. economicSector - array[string]
  10. tension - array[string]
  11. timeDiscrimination - array[string]
  12. sort

This is the expected .json format:

[
    {
    "sumEnergy":Number,                         Suma de energĂ­a (kWh)
    "sumContract":Number                        Suma de contratos
    }
  ]
                   

And here is a .json response example:

 [
    {
    "sumEnergy":1863572529,
    "sumContract":3425358   
    }
  ]

Could anyone give me some help with that, please?
I am stuck since a while now…

Thank you very much in advance!

What is this library? I can’t find it in Python’s standard library :confused: OK, I found it, sorry :blush:

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 :slight_smile:

1 Like

Thank you for your answer @FelixLeg. Happy to read you again!

What does this mean in concrete terms? I can’t extract API data with Python?
Is R more suitable in this case, or any other software?

Thank you very much for your reply!
Best,

Michael

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.

1 Like

@FelixLeg,

Thank you so much! I understand clearly now. It will probably be very cumbersome, I guess, to do it manually…

Thank you so much for your time.
All the best,

Michael

1 Like