11from __future__ import annotations
22
33import os
4+ import warnings
45from importlib import import_module
56from typing import TYPE_CHECKING , Literal
67from urllib .parse import urljoin
1112from monty .json import MontyDecoder
1213from 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
1516from mp_api .client .core .settings import MAPI_CLIENT_SETTINGS
1617
1718if 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
0 commit comments