|
| 1 | +"""OpenAlex 학술 그래프 읽기 계약(contract). |
| 2 | +
|
| 3 | +상류 API의 '진실'만 담는다 — 엔드포인트 상수, 경로 빌더, 쿼리 제약/빌더, 응답 모델. |
| 4 | +MCP/네트워크 무의존(순수 상수 + pydantic 모델). |
| 5 | +
|
| 6 | +전부 GET·JSON·읽기. 인증은 **선택**(키 없이도 동작). 키(`api_key`)와 polite-pool 이메일 |
| 7 | +(`mailto`)은 **쿼리 파라미터**다(헤더 아님). 페이지네이션/건수는 **응답 본문 meta**에 실리므로 |
| 8 | +코어 `get_json`만으로 충분하다(헤더 동사 불필요). |
| 9 | +
|
| 10 | +출처(공식 문서 — developers.openalex.org): |
| 11 | + - API 개요(base URL): https://developers.openalex.org/how-to-use-the-api/api-overview |
| 12 | + - 리스트/검색(search·filter·sort·per-page·page·cursor·meta 봉투): |
| 13 | + https://developers.openalex.org/how-to-use-the-api/get-lists-of-entities |
| 14 | + - Work 오브젝트(필드): https://developers.openalex.org/api-entities/works/work-object |
| 15 | + - Author 오브젝트(필드): https://developers.openalex.org/api-entities/authors/author-object |
| 16 | + - 인증/요금(api_key·mailto polite pool·레이트리밋): https://developers.openalex.org/guides/authentication |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import re |
| 22 | + |
| 23 | +from pydantic import BaseModel |
| 24 | + |
| 25 | +# ─── base URL / 엔드포인트 상수 ───────────────────────────── |
| 26 | +# 출처(base): https://developers.openalex.org/how-to-use-the-api/api-overview |
| 27 | +# ("https://api.openalex.org") |
| 28 | +# 출처(엔드포인트 /works·/authors): get-lists-of-entities (entity 컬렉션 경로) |
| 29 | +BASE_URL = "https://api.openalex.org" |
| 30 | +WORKS = "/works" |
| 31 | +AUTHORS = "/authors" |
| 32 | + |
| 33 | + |
| 34 | +# bare DOI/ORCID는 OpenAlex가 거부(404)한다 — 네임스페이스 접두(doi:/orcid:)나 URL이라야 한다 |
| 35 | +# ("a bare identifier without any prefix or URL wrapper is not supported"). 자동 정규화한다. |
| 36 | +# OpenAlex ID(W…/A…)·전체 URL·이미 접두가 붙은 값은 그대로 둔다. |
| 37 | +_BARE_DOI = re.compile(r"^10\.\d{4,9}/.+$", re.IGNORECASE) |
| 38 | +_BARE_ORCID = re.compile(r"^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$", re.IGNORECASE) |
| 39 | + |
| 40 | + |
| 41 | +def normalize_work_id(work_id: str) -> str: |
| 42 | + """bare DOI(`10.x/...`)면 `doi:` 접두를 붙인다(OpenAlex ID·URL·접두값은 그대로).""" |
| 43 | + wid = work_id.strip() |
| 44 | + return f"doi:{wid}" if _BARE_DOI.match(wid) else wid |
| 45 | + |
| 46 | + |
| 47 | +def normalize_author_id(author_id: str) -> str: |
| 48 | + """bare ORCID(`0000-0000-0000-0000`)면 `orcid:` 접두를 붙인다(OpenAlex ID·URL은 그대로).""" |
| 49 | + aid = author_id.strip() |
| 50 | + return f"orcid:{aid}" if _BARE_ORCID.match(aid) else aid |
| 51 | + |
| 52 | + |
| 53 | +def work_path(work_id: str) -> str: |
| 54 | + """단건 work 경로 /works/{id}. id = OpenAlex ID(`W…`)·DOI(bare/doi:/URL)·기타 접두. |
| 55 | +
|
| 56 | + bare DOI는 `doi:`로 정규화한다(라이브 확인: bare DOI는 404, `doi:`는 200). |
| 57 | + 출처: https://developers.openalex.org/api-entities/works/work-object |
| 58 | + """ |
| 59 | + return f"{WORKS}/{normalize_work_id(work_id)}" |
| 60 | + |
| 61 | + |
| 62 | +def author_path(author_id: str) -> str: |
| 63 | + """단건 author 경로 /authors/{id}. id = OpenAlex ID(`A…`)·ORCID(bare/orcid:/URL). |
| 64 | +
|
| 65 | + bare ORCID는 `orcid:`로 정규화한다. |
| 66 | + 출처: https://developers.openalex.org/api-entities/authors/author-object |
| 67 | + """ |
| 68 | + return f"{AUTHORS}/{normalize_author_id(author_id)}" |
| 69 | + |
| 70 | + |
| 71 | +# ─── 쿼리 파라미터 제약(공식) ─────────────────────────────── |
| 72 | +# 출처: https://developers.openalex.org/how-to-use-the-api/get-lists-of-entities |
| 73 | +# ("per-page" 1–200, page 기반 페이지네이션은 최대 10,000건까지 — 이후 cursor) |
| 74 | +# 주의: **쿼리 파라미터명은 `per-page`(하이픈)**, 응답 본문 필드명은 `per_page`(언더스코어). |
| 75 | +DEFAULT_PER_PAGE = 25 |
| 76 | +MIN_PER_PAGE = 1 |
| 77 | +MAX_PER_PAGE = 200 |
| 78 | +MAX_PAGE_RESULTS = 10000 |
| 79 | + |
| 80 | +# 공식 쿼리 파라미터명(정확한 철자 — 하이픈/언더스코어 혼동 방지). |
| 81 | +# 출처: get-lists-of-entities(search·filter·sort·per-page·page) + authentication(api_key·mailto) |
| 82 | +PARAM_SEARCH = "search" |
| 83 | +PARAM_FILTER = "filter" |
| 84 | +PARAM_SORT = "sort" |
| 85 | +PARAM_PER_PAGE = "per-page" # 하이픈! |
| 86 | +PARAM_PAGE = "page" |
| 87 | +PARAM_API_KEY = "api_key" |
| 88 | +PARAM_MAILTO = "mailto" |
| 89 | + |
| 90 | + |
| 91 | +def validate_per_page(per_page: int) -> int: |
| 92 | + """per-page를 1..200 범위로 검증한다(공식 제약). |
| 93 | +
|
| 94 | + 위반 시 ValueError(상류가 `{"error":...,"message":"...must be between 1 and 200"}`로 |
| 95 | + 400을 주기 전에 미리 막는다). |
| 96 | + 출처: https://developers.openalex.org/how-to-use-the-api/get-lists-of-entities |
| 97 | + """ |
| 98 | + if per_page < MIN_PER_PAGE or per_page > MAX_PER_PAGE: |
| 99 | + raise ValueError( |
| 100 | + f"per_page는 {MIN_PER_PAGE}..{MAX_PER_PAGE} 범위여야 합니다(현재 {per_page})." |
| 101 | + ) |
| 102 | + return per_page |
| 103 | + |
| 104 | + |
| 105 | +def build_params( |
| 106 | + *, |
| 107 | + query: str | None = None, |
| 108 | + filter: str | None = None, # noqa: A002 (공식 파라미터명 "filter") |
| 109 | + sort: str | None = None, |
| 110 | + per_page: int | None = None, |
| 111 | + page: int | None = None, |
| 112 | + api_key: str | None = None, |
| 113 | + mailto: str | None = None, |
| 114 | +) -> dict[str, str | int]: |
| 115 | + """리스트/검색 쿼리스트링을 만든다. None/빈값은 생략한다. |
| 116 | +
|
| 117 | + - query → `search`(전문 검색) |
| 118 | + - filter → `filter`(attr:value, 콤마=AND / `|`=OR / `!`=NOT) |
| 119 | + - sort → `sort` |
| 120 | + - per_page → `per-page`(하이픈! 1..200 검증) |
| 121 | + - page → `page` |
| 122 | + - api_key → `api_key`(쿼리 파라미터, 선택) |
| 123 | + - mailto → `mailto`(polite pool, 선택) |
| 124 | + 출처: https://developers.openalex.org/how-to-use-the-api/get-lists-of-entities |
| 125 | + + https://developers.openalex.org/guides/authentication |
| 126 | + """ |
| 127 | + params: dict[str, str | int] = {} |
| 128 | + if query: |
| 129 | + params[PARAM_SEARCH] = query |
| 130 | + if filter: |
| 131 | + params[PARAM_FILTER] = filter |
| 132 | + if sort: |
| 133 | + params[PARAM_SORT] = sort |
| 134 | + if per_page is not None: |
| 135 | + params[PARAM_PER_PAGE] = validate_per_page(per_page) |
| 136 | + if page is not None: |
| 137 | + params[PARAM_PAGE] = page |
| 138 | + if api_key: |
| 139 | + params[PARAM_API_KEY] = api_key |
| 140 | + if mailto: |
| 141 | + params[PARAM_MAILTO] = mailto |
| 142 | + return params |
| 143 | + |
| 144 | + |
| 145 | +# ─── 응답 모델 ────────────────────────────────────────────── |
| 146 | +# 리스트 응답 봉투: {"meta":{...}, "results":[...], "group_by":[]}. |
| 147 | +# 단건은 entity 오브젝트가 곧 최상위. extra="ignore"로 느슨히 받고(부분 모델), |
| 148 | +# 확신하는 필드만 모델링한다. |
| 149 | +# 출처(봉투/meta): https://developers.openalex.org/how-to-use-the-api/get-lists-of-entities |
| 150 | + |
| 151 | + |
| 152 | +class Meta(BaseModel): |
| 153 | + """리스트 응답의 meta 봉투. |
| 154 | +
|
| 155 | + count(총 건수)·page·per_page(언더스코어!)·next_cursor(cursor 페이지네이션 시). |
| 156 | + cost_usd는 라이브 응답에서 관측됨 → float|None로 느슨히 둔다. |
| 157 | + 출처: https://developers.openalex.org/how-to-use-the-api/get-lists-of-entities |
| 158 | + """ |
| 159 | + |
| 160 | + model_config = {"extra": "ignore"} |
| 161 | + |
| 162 | + count: int |
| 163 | + page: int | None = None |
| 164 | + per_page: int | None = None # 응답 본문 필드는 per_page(언더스코어) |
| 165 | + next_cursor: str | None = None |
| 166 | + cost_usd: float | None = None # 라이브 관측 — 공식 산문에 표준화 명시는 약함 |
| 167 | + |
| 168 | + |
| 169 | +class Work(BaseModel): |
| 170 | + """단일 Work 오브젝트(부분). |
| 171 | +
|
| 172 | + 공식 필드: id · doi · display_name(+ title 별칭) · publication_year · |
| 173 | + publication_date · type · cited_by_count · authorships(각 author.display_name/id) · |
| 174 | + primary_location · open_access. |
| 175 | + 출처: https://developers.openalex.org/api-entities/works/work-object |
| 176 | + """ |
| 177 | + |
| 178 | + model_config = {"extra": "ignore"} |
| 179 | + |
| 180 | + id: str |
| 181 | + doi: str | None = None |
| 182 | + display_name: str | None = None |
| 183 | + title: str | None = None # 공식상 display_name의 별칭 |
| 184 | + publication_year: int | None = None |
| 185 | + publication_date: str | None = None |
| 186 | + type: str | None = None |
| 187 | + cited_by_count: int | None = None |
| 188 | + authorships: list[dict] | None = None # 각 항목 author.display_name/author.id → dict로 느슨히 |
| 189 | + primary_location: dict | None = None |
| 190 | + open_access: dict | None = None |
| 191 | + |
| 192 | + |
| 193 | +class Author(BaseModel): |
| 194 | + """단일 Author 오브젝트(부분). |
| 195 | +
|
| 196 | + 공식 필드: id · display_name · orcid · works_count · cited_by_count. |
| 197 | + 출처: https://developers.openalex.org/api-entities/authors/author-object |
| 198 | + """ |
| 199 | + |
| 200 | + model_config = {"extra": "ignore"} |
| 201 | + |
| 202 | + id: str |
| 203 | + display_name: str | None = None |
| 204 | + orcid: str | None = None |
| 205 | + works_count: int | None = None |
| 206 | + cited_by_count: int | None = None |
| 207 | + |
| 208 | + |
| 209 | +class WorksList(BaseModel): |
| 210 | + """`/works` 리스트 응답 봉투. |
| 211 | +
|
| 212 | + 출처: https://developers.openalex.org/how-to-use-the-api/get-lists-of-entities |
| 213 | + """ |
| 214 | + |
| 215 | + model_config = {"extra": "ignore"} |
| 216 | + |
| 217 | + meta: Meta |
| 218 | + results: list[Work] = [] |
| 219 | + |
| 220 | + |
| 221 | +class AuthorsList(BaseModel): |
| 222 | + """`/authors` 리스트 응답 봉투. |
| 223 | +
|
| 224 | + 출처: https://developers.openalex.org/how-to-use-the-api/get-lists-of-entities |
| 225 | + """ |
| 226 | + |
| 227 | + model_config = {"extra": "ignore"} |
| 228 | + |
| 229 | + meta: Meta |
| 230 | + results: list[Author] = [] |
| 231 | + |
| 232 | + |
| 233 | +class ErrorResponse(BaseModel): |
| 234 | + """OpenAlex 에러 봉투 `{error, message}`. |
| 235 | +
|
| 236 | + 예: per-page 범위 위반 시 message="...must be between 1 and 200". |
| 237 | + 출처: https://developers.openalex.org/how-to-use-the-api/get-lists-of-entities |
| 238 | + """ |
| 239 | + |
| 240 | + model_config = {"extra": "ignore"} |
| 241 | + |
| 242 | + error: str | None = None |
| 243 | + message: str | None = None |
0 commit comments