import json from typing import Any from urllib.error import HTTPError, URLError from urllib.parse import urlencode from urllib.request import Request, urlopen OPENALEX_WORKS_URL = "https://api.openalex.org/works" REQUEST_TIMEOUT_SECONDS = 30 PER_PAGE = 200 def normalize_author_id(author_id: str) -> str: """ Normalizes OpenAlex author IDs. Supported inputs: - A123456789 - https://openalex.org/A123456789 - https://api.openalex.org/authors/A123456789 """ cleaned_author_id = author_id.strip() if cleaned_author_id.startswith("https://api.openalex.org/authors/"): return cleaned_author_id.replace( "https://api.openalex.org/authors/", "https://openalex.org/", ) if cleaned_author_id.startswith("https://openalex.org/"): return cleaned_author_id if cleaned_author_id.startswith("A"): return f"https://openalex.org/{cleaned_author_id}" return cleaned_author_id def fetch_openalex_page( author_id: str, cursor: str, select: str | None = None ) -> dict[str, Any]: normalized_author_id = normalize_author_id(author_id) params = { "filter": f"authorships.author.id:{normalized_author_id}", "per-page": PER_PAGE, "cursor": cursor, "sort": "publication_year:asc", } if select: params["select"] = select query_params = urlencode(params) url = f"{OPENALEX_WORKS_URL}?{query_params}" request = Request( url, headers={ "Accept": "application/json", "User-Agent": "AIIS career stage analysis", }, ) try: with urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: response_body = response.read().decode("utf-8") return json.loads(response_body) except HTTPError as error: raise RuntimeError( f"OpenAlex request failed with HTTP status {error.code}: {url}" ) from error except URLError as error: raise RuntimeError(f"OpenAlex request failed: {error}") from error def get_all_author_works( author_id: str, select: str | None = None ) -> list[dict[str, Any]]: """ Fetches all works for an OpenAlex author by using cursor pagination. `select` restricts the returned fields (comma-separated OpenAlex field names) to keep responses small when only a few fields are needed. """ works: list[dict[str, Any]] = [] cursor = "*" while cursor: data = fetch_openalex_page(author_id, cursor, select=select) page_results = data.get("results", []) works.extend(page_results) meta = data.get("meta", {}) next_cursor = meta.get("next_cursor") if not next_cursor or next_cursor == cursor: break cursor = next_cursor return works