ecmwf / cdsapi

Python API to access the Copernicus Climate Data Store (CDS)
Apache License 2.0
230 stars 56 forks source link

Add a "check authentication" function #111

Open veenstrajelmer opened 1 month ago

veenstrajelmer commented 1 month ago

Is your feature request related to a problem? Please describe.

When running c = cdsapi.Client() it checks whether there is a CDS apikey in the CDSAPI_KEY environment variable or in the ~/.cdsapirc file. This is useful. However, it does not check whether this key works. When you want to check if a user is indeed authorized (the apikey is correct) and properly catch it if it is not the case (but pass if authentication succeeds), one would have to do something like this:

# check if the authentication works
try:
    # checks whether CDS apikey is in environment variable or ~/.cdsapirc file
    c = cdsapi.Client()
    # checks whether authentication is succesful (correct combination of url and apikey)
    c.retrieve(name='dummy', request={})
except RuntimeError as e:
    if "dataset dummy not found" in str(e):
        # catching incorrect name, but authentication was successful
        print('found ECMWF API-key and authorization successful')
    elif "Authentication failed" in str(e):
        cds_remove_credentials_raise(reason='Authentication failed')
    else:
        raise e

Describe the solution you'd like

It would already be helpful if not all cdsapi errors would be RuntimeErrors. A specific cdsapi AuthenticationFailedError would be useful. What would be even better is if there would be a function available that checks the authentication. Something like this:

c = cdsapi.Client()
c.check_authentication()

This function then fails if the apikey is incorrect (or authentication fails for another reason). Could this be added?

Describe alternatives you've considered

The cumbersome workaround above.

Additional context

If there is no ~/.cdsapirc file yet, we get Exception("Missing/incomplete configuration file"). It would be convenient if this generic Exception is replaced with a standard FileNotFoundError so this specific error can be catched more easily.

Organisation

Deltares

ALopAlos commented 1 month ago

Thanks for your proposal. We are evaluating it.

veenstrajelmer commented 2 weeks ago

Is it already being evalutated? I now test this by requesting "dummy" dataset, and then catch the Exception for a nonexistent dataset, I get a HTTPError when the authentication fails. The exception used to be a RuntimeError, so from 0.7.0 to 0.7.2 my code broke. I would really just like to have a method in cdsapi that checks whether the authentication is valid and returns a boolean (or an error)