Skip to content

Commit 9625174

Browse files
only warn if api key is not set to allow server to work
1 parent ac296fa commit 9625174

2 files changed

Lines changed: 16 additions & 7 deletions

File tree

mp_api/client/core/utils.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import os
4+
import warnings
45
from importlib import import_module
56
from typing import TYPE_CHECKING, Literal
67
from urllib.parse import urljoin
@@ -11,7 +12,7 @@
1112
from monty.json import MontyDecoder
1213
from packaging.version import parse as parse_version
1314

14-
from mp_api.client.core.exceptions import MPRestError
15+
from mp_api.client.core.exceptions import MPRestError, MPRestWarning
1516
from mp_api.client.core.settings import MAPI_CLIENT_SETTINGS
1617

1718
if TYPE_CHECKING:
@@ -54,7 +55,7 @@ def load_json(
5455
return MontyDecoder().process_decoded(data) if deser else data
5556

5657

57-
def validate_api_key(api_key: str | None = None) -> str:
58+
def validate_api_key(api_key: str | None = None) -> str | None:
5859
"""Find and validate an API key."""
5960
# SETTINGS tries to read API key from ~/.config/.pmgrc.yaml
6061
api_key = api_key or os.getenv("MP_API_KEY")
@@ -63,11 +64,19 @@ def validate_api_key(api_key: str | None = None) -> str:
6364

6465
api_key = PMG_SETTINGS.get("PMG_MAPI_KEY")
6566

66-
if not api_key or len(api_key) != 32:
67-
addendum = " Valid API keys are 32 characters." if api_key else ""
67+
if not api_key:
68+
warnings.warn(
69+
"No API key found, please set explicitly or in "
70+
"the `MP_API_KEY` environment variable.",
71+
category=MPRestWarning,
72+
stacklevel=2,
73+
)
74+
75+
elif isinstance(api_key, str) and len(api_key) != 32:
6876
raise MPRestError(
6977
"Please obtain a valid API key from https://materialsproject.org/api "
70-
f"and export it as an environment variable `MP_API_KEY`.{addendum}"
78+
"and export it as an environment variable `MP_API_KEY`. "
79+
"Valid API keys are 32 characters."
7180
)
7281

7382
return api_key

tests/client/test_mprester.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -430,8 +430,8 @@ def test_get_default_api_key_endpoint(self, monkeypatch: pytest.MonkeyPatch):
430430
monkeypatch.delenv("MP_API_KEY", raising=False)
431431
monkeypatch.delenv("PMG_MAPI_KEY", raising=False)
432432
monkeypatch.setitem(SETTINGS, "PMG_MAPI_KEY", None)
433-
with pytest.raises(MPRestError, match="Please obtain a valid API key"):
434-
MPRester().get_structure_by_material_id("mp-149")
433+
with pytest.warns(MPRestWarning, match="No API key found"):
434+
MPRester()
435435

436436
def test_invalid_api_key(self, monkeypatch):
437437
monkeypatch.setenv("MP_API_KEY", "INVALID")

0 commit comments

Comments
 (0)