44import os
55from collections .abc import Collection
66from datetime import datetime
7+ from functools import cache
78from typing import Any
89from urllib .parse import quote
910
@@ -35,19 +36,26 @@ def reformat_name(name: str) -> str:
3536 return f"{ given_names } { family } "
3637
3738
39+ @cache
3840def get_openalex_mailto () -> str | None :
39- """Get the OpenAlex mailto address.
40-
41- Returns:
42- The OpenAlex mailto address if available.
43- """
44- mailto_address = os .environ .get ("OPENALEX_MAILTO" )
41+ """Get the OpenAlex mailto address, if available."""
42+ mailto_address = os .getenv ("OPENALEX_MAILTO" )
4543 if mailto_address is None :
4644 logger .warning (
4745 "OPENALEX_MAILTO environment variable not set."
4846 " your request may be deprioritized by OpenAlex."
4947 )
50- return os .environ .get ("OPENALEX_MAILTO" )
48+ return mailto_address
49+
50+
51+ @cache
52+ def get_openalex_api_key () -> str | None :
53+ """
54+ Get the OpenAlex API key from 'OPENALEX_API_KEY' if available, for premium features.
55+
56+ SEE: https://github.com/ourresearch/openalex-api-tutorials/blob/main/notebooks/getting-started/premium.ipynb
57+ """
58+ return os .getenv ("OPENALEX_API_KEY" )
5159
5260
5361async def get_doc_details_from_openalex (
@@ -75,6 +83,8 @@ async def get_doc_details_from_openalex(
7583 """
7684 mailto = get_openalex_mailto ()
7785 params = {"mailto" : mailto } if mailto else {}
86+ api_key = get_openalex_api_key ()
87+ headers = {"api_key" : api_key } if api_key else {}
7888
7989 if doi is title is None :
8090 raise ValueError ("Either a DOI or title must be provided." )
@@ -95,7 +105,7 @@ async def get_doc_details_from_openalex(
95105 # being thrown for DOIs 10.1046/j.1365-2699.2003.00795 and 10.2147/cia.s3785,
96106 # even with up to 3 retries
97107 response = await client .get (
98- url , params = params , timeout = OPENALEX_API_REQUEST_TIMEOUT
108+ url , params = params , headers = headers , timeout = OPENALEX_API_REQUEST_TIMEOUT
99109 )
100110 try :
101111 response .raise_for_status ()
0 commit comments