1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
|
from __future__ import annotations
import contextlib
import typing
from time import sleep
import requests
from crossref import VERSION, validators
LIMIT = 100
MAXOFFSET = 10000
FACETS_MAX_LIMIT = 1000
API = "api.crossref.org"
class CrossrefAPIError(Exception):
pass
class MaxOffsetError(CrossrefAPIError):
pass
class UrlSyntaxError(CrossrefAPIError, ValueError):
pass
class HTTPRequest:
def __init__(self, throttle=True):
self.throttle = throttle
self.rate_limits = {"x-rate-limit-limit": 50, "x-rate-limit-interval": 1}
def _update_rate_limits(self, headers):
with contextlib.suppress(ValueError):
self.rate_limits["x-rate-limit-limit"] = int(headers.get("x-rate-limit-limit", 50))
with contextlib.suppress(ValueError):
interval_value = int(headers.get("x-rate-limit-interval", "1s")[:-1])
interval_scope = headers.get("x-rate-limit-interval", "1s")[-1]
if interval_scope == "m":
interval_value = interval_value * 60
if interval_scope == "h":
interval_value = interval_value * 60 * 60
self.rate_limits["x-rate-limit-interval"] = interval_value
@property
def throttling_time(self):
return self.rate_limits["x-rate-limit-interval"] / self.rate_limits["x-rate-limit-limit"]
def do_http_request( # noqa: PLR0913
self,
method,
endpoint,
data=None,
files=None,
timeout=100,
only_headers=False,
custom_header=None,
):
if only_headers is True:
return requests.head(endpoint, timeout=2)
action = requests.post if method == "post" else requests.get
headers = custom_header if custom_header else {"user-agent": str(Etiquette())}
if method == "post":
result = action(endpoint, data=data, files=files, timeout=timeout, headers=headers)
else:
result = action(endpoint, params=data, timeout=timeout, headers=headers)
if self.throttle is True:
self._update_rate_limits(result.headers)
sleep(self.throttling_time)
return result
def build_url_endpoint(endpoint, context=None):
endpoint = "/".join([i for i in [context, endpoint] if i])
return f"https://{API}/{endpoint}"
class Etiquette:
def __init__(
self,
application_name="undefined",
application_version="undefined",
application_url="undefined",
contact_email="anonymous",
):
self.application_name = application_name
self.application_version = application_version
self.application_url = application_url
self.contact_email = contact_email
def __str__(self):
return "{}/{} ({}; mailto:{}) BasedOn: CrossrefAPI/{}".format(
self.application_name,
self.application_version,
self.application_url,
self.contact_email,
VERSION,
)
class Endpoint:
CURSOR_AS_ITER_METHOD = False
def __init__( # noqa: PLR0913
self,
request_url=None,
request_params=None,
context=None,
etiquette=None,
throttle=True,
crossref_plus_token=None,
timeout=30,
):
self.do_http_request = HTTPRequest(throttle=throttle).do_http_request
self.etiquette = etiquette or Etiquette()
self.custom_header = {"user-agent": str(self.etiquette)}
self.crossref_plus_token = crossref_plus_token
if crossref_plus_token:
self.custom_header["Crossref-Plus-API-Token"] = self.crossref_plus_token
self.request_url = request_url or build_url_endpoint(self.ENDPOINT, context)
self.request_params = request_params or {}
self.context = context or ""
self.timeout = timeout
@property
def _rate_limits(self):
request_url = str(self.request_url)
result = self.do_http_request(
"get",
request_url,
only_headers=True,
custom_header=self.custom_header,
timeout=self.timeout,
throttle=False,
)
return {
"x-rate-limit-limit": result.headers.get("x-rate-limit-limit", "undefined"),
"x-rate-limit-interval": result.headers.get("x-rate-limit-interval", "undefined"),
}
def _escaped_pagging(self):
escape_pagging = ["offset", "rows"]
request_params = dict(self.request_params)
for item in escape_pagging:
with contextlib.suppress(KeyError):
del request_params[item]
return request_params
@property
def version(self):
"""
This attribute retrieve the API version.
>>> Works().version
'1.0.0'
"""
request_params = dict(self.request_params)
request_url = str(self.request_url)
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
).json()
return result["message-version"]
@property
def x_rate_limit_limit(self):
return self._rate_limits.get("x-rate-limit-limit", "undefined")
@property
def x_rate_limit_interval(self):
return self._rate_limits.get("x-rate-limit-interval", "undefined")
def count(self):
"""
This method retrieve the total of records resulting from a given query.
This attribute can be used compounded with query, filter,
sort, order and facet methods.
Examples:
>>> from crossref.restful import Works
>>> Works().query('zika').count()
3597
>>> Works().query('zika').filter(prefix='10.1590').count()
61
>>> Works().query('zika').filter(prefix='10.1590').sort('published') \
.order('desc').filter(has_abstract='true').count()
14
>>> Works().query('zika').filter(prefix='10.1590').sort('published') \
.order('desc').filter(has_abstract='true').query(author='Marli').count()
1
"""
request_params = dict(self.request_params)
request_url = str(self.request_url)
request_params["rows"] = 0
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
).json()
return int(result["message"]["total-results"])
@property
def url(self):
"""
This attribute retrieve the url that will be used as a HTTP request to
the Crossref API.
This attribute can be used compounded with query, filter,
sort, order and facet methods.
Examples:
>>> from crossref.restful import Works
>>> Works().query('zika').url
'https://api.crossref.org/works?query=zika'
>>> Works().query('zika').filter(prefix='10.1590').url
'https://api.crossref.org/works?query=zika&filter=prefix%3A10.1590'
>>> Works().query('zika').filter(prefix='10.1590').sort('published') \
.order('desc').url
'https://api.crossref.org/works?sort=published
&order=desc&query=zika&filter=prefix%3A10.1590'
>>> Works().query('zika').filter(prefix='10.1590').sort('published') \
.order('desc').filter(has_abstract='true').query(author='Marli').url
'https://api.crossref.org/works?sort=published
&filter=prefix%3A10.1590%2Chas-abstract%3Atrue&query=zika&order=desc&query.author=Marli'
"""
request_params = self._escaped_pagging()
sorted_request_params = sorted([(k, v) for k, v in request_params.items()])
req = requests.Request("get", self.request_url, params=sorted_request_params).prepare()
return req.url
def all(self, request_params: dict | None): # noqa: A003
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT, context)
if request_params is None:
request_params = {}
return iter(
self.__class__(
request_url=request_url,
request_params=request_params,
context=context,
etiquette=self.etiquette,
crossref_plus_token=self.crossref_plus_token,
timeout=self.timeout,
),
)
def __iter__(self): # noqa: PLR0912 - To many branches is not a problem.
request_url = str(self.request_url)
if "sample" in self.request_params:
request_params = self._escaped_pagging()
result = self.do_http_request(
"get",
self.request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return
result = result.json()
for item in result["message"]["items"]:
yield item
return
if self.CURSOR_AS_ITER_METHOD is True:
request_params = dict(self.request_params)
request_params["cursor"] = "*"
request_params["rows"] = LIMIT
while True:
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return
result = result.json()
if len(result["message"]["items"]) == 0:
return
for item in result["message"]["items"]:
yield item
request_params["cursor"] = result["message"]["next-cursor"]
else:
request_params = dict(self.request_params)
request_params["offset"] = 0
request_params["rows"] = LIMIT
while True:
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return
result = result.json()
if len(result["message"]["items"]) == 0:
return
for item in result["message"]["items"]:
yield item
request_params["offset"] += LIMIT
if request_params["offset"] >= MAXOFFSET:
msg = "Offset exceded the max offset of %d"
raise MaxOffsetError(msg, MAXOFFSET)
class Works(Endpoint):
CURSOR_AS_ITER_METHOD = True
ENDPOINT = "works"
ORDER_VALUES = ("asc", "desc", "1", "-1")
SORT_VALUES = (
"created",
"deposited",
"indexed",
"is-referenced-by-count",
"issued",
"published",
"published-online",
"published-print",
"references-count",
"relevance",
"score",
"submitted",
"updated",
)
FIELDS_QUERY = (
"affiliation",
"author",
"bibliographic",
"chair",
"container_title",
"contributor",
"editor",
"event_acronym",
"event_location",
"event_name",
"event_sponsor",
"event_theme",
"funder_name",
"publisher_location",
"publisher_name",
"translator",
)
FIELDS_SELECT = (
"DOI",
"ISBN",
"ISSN",
"URL",
"abstract",
"accepted",
"alternative-id",
"approved",
"archive",
"article-number",
"assertion",
"author",
"chair",
"clinical-trial-number",
"container-title",
"content-created",
"content-domain",
"created",
"degree",
"deposited",
"editor",
"event",
"funder",
"group-title",
"indexed",
"is-referenced-by-count",
"issn-type",
"issue",
"issued",
"license",
"link",
"member",
"original-title",
"page",
"posted",
"prefix",
"published",
"published-online",
"published-print",
"publisher",
"publisher-location",
"reference",
"references-count",
"relation",
"score",
"short-container-title",
"short-title",
"standards-body",
"subject",
"subtitle",
"title",
"translator",
"type",
"update-policy",
"update-to",
"updated-by",
"volume",
)
FILTER_VALIDATOR: typing.ClassVar[dict] = {
"alternative_id": None,
"archive": validators.archive,
"article_number": None,
"assertion": None,
"assertion-group": None,
"award.funder": None,
"award.number": None,
"category-name": None,
"clinical-trial-number": None,
"container-title": None,
"content-domain": None,
"directory": validators.directory,
"doi": None,
"from-accepted-date": validators.is_date,
"from-created-date": validators.is_date,
"from-deposit-date": validators.is_date,
"from-event-end-date": validators.is_date,
"from-event-start-date": validators.is_date,
"from-index-date": validators.is_date,
"from-issued-date": validators.is_date,
"from-online-pub-date": validators.is_date,
"from-posted-date": validators.is_date,
"from-print-pub-date": validators.is_date,
"from-pub-date": validators.is_date,
"from-update-date": validators.is_date,
"full-text.application": None,
"full-text.type": None,
"full-text.version": None,
"funder": None,
"funder-doi-asserted-by": None,
"group-title": None,
"has-abstract": validators.is_bool,
"has-affiliation": validators.is_bool,
"has-archive": validators.is_bool,
"has-assertion": validators.is_bool,
"has-authenticated-orcid": validators.is_bool,
"has-award": validators.is_bool,
"has-clinical-trial-number": validators.is_bool,
"has-content-domain": validators.is_bool,
"has-domain-restriction": validators.is_bool,
"has-event": validators.is_bool,
"has-full-text": validators.is_bool,
"has-funder": validators.is_bool,
"has-funder-doi": validators.is_bool,
"has-license": validators.is_bool,
"has-orcid": validators.is_bool,
"has-references": validators.is_bool,
"has-relation": validators.is_bool,
"has-update": validators.is_bool,
"has-update-policy": validators.is_bool,
"is-update": validators.is_bool,
"isbn": None,
"issn": None,
"license.delay": validators.is_integer,
"license.url": None,
"license.version": None,
"location": None,
"member": validators.is_integer,
"orcid": None,
"prefix": None,
"relation.object": None,
"relation.object-type": None,
"relation.type": None,
"type": validators.document_type,
"type-name": None,
"until-accepted-date": validators.is_date,
"until-created-date": validators.is_date,
"until-deposit-date": validators.is_date,
"until-event-end-date": validators.is_date,
"until-event-start-date": validators.is_date,
"until-index-date": validators.is_date,
"until-issued-date": validators.is_date,
"until-online-pub-date": validators.is_date,
"until-posted-date": validators.is_date,
"until-print-pub-date": validators.is_date,
"until-pub-date": validators.is_date,
"until-update-date": validators.is_date,
"update-type": None,
"updates": None,
}
FACET_VALUES: typing.ClassVar[dict] = {
"archive": None,
"affiliation": None,
"assertion": None,
"assertion-group": None,
"category-name": None,
"container-title": 1000,
"license": None,
"funder-doi": None,
"funder-name": None,
"issn": 1000,
"orcid": 1000,
"published": None,
"publisher-name": None,
"relation-type": None,
"source": None,
"type-name": None,
"update-type": None,
}
def order(self, order="asc"):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded with query, filter,
sort and facet methods.
kwargs: valid SORT_VALUES arguments.
return: iterable object of Works metadata
Example 1:
>>> from crossref.restful import Works
>>> works.query('zika').sort('deposited').order('asc').url
'https://api.crossref.org/works?sort=deposited&query=zika&order=asc'
>>> query = works.query('zika').sort('deposited').order('asc')
>>> for item in query:
... print(item['title'], item['deposited']['date-time'])
...
['A Facile Preparation of ... an-1-one'] 2007-02-13T20:56:13Z
['Contributions to the F ... Vermont, III'] 2007-02-13T20:56:13Z
['Pilularia americana A. Braun in Klamath County, Oregon'] 2007-02-13T20:56:13Z
...
Example 2:
>>> from crossref.restful import Works
>>> works.query('zika').sort('deposited').order('desc').url
'https://api.crossref.org/works?sort=deposited&query=zika&order=desc'
>>> query = works.query('zika').sort('deposited').order('desc')
>>> for item in query:
... print(item['title'], item['deposited']['date-time'])
...
["Planning for the unexpected: ... , Zika virus, what's next?"] 2017-05-29T12:55:53Z
['Sensitivity of RT-PCR method ... or competence studies'] 2017-05-29T12:53:54Z
['Re-evaluation of routine den ... a of Zika virus emergence'] 2017-05-29T10:46:11Z
...
"""
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT, context)
request_params = dict(self.request_params)
if order not in self.ORDER_VALUES:
msg = "Sort order specified as {} but must be one of: {}".format(str(order), ", ".join(
self.ORDER_VALUES))
raise UrlSyntaxError(
msg,
)
request_params["order"] = order
return self.__class__(
request_url=request_url,
request_params=request_params,
context=context,
etiquette=self.etiquette,
timeout=self.timeout,
)
def select(self, *args):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded with query, filter,
sort and facet methods.
args: valid FIELDS_SELECT arguments.
return: iterable object of Works metadata
Example 1:
>>> from crossref.restful import Works
>>> works = Works()
>>> for i in works.filter(has_funder='true', has_license='true') \
.sample(5).select('DOI, prefix'):
... print(i)
...
{'DOI': '10.1016/j.jdiacomp.2016.06.005', 'prefix': '10.1016'}
{'DOI': '10.1016/j.mssp.2015.07.076', 'prefix': '10.1016'}
{'DOI': '10.1002/slct.201700168', 'prefix': '10.1002'}
{'DOI': '10.1016/j.actbio.2017.01.034', 'prefix': '10.1016'}
{'DOI': '10.1016/j.optcom.2013.11.013', 'prefix': '10.1016'}
...
Example 2:
>>> from crossref.restful import Works
>>> works = Works()
>>> for i in works.filter(has_funder='true', has_license='true') \
.sample(5).select('DOI').select('prefix'):
>>> print(i)
...
{'DOI': '10.1016/j.sajb.2016.03.010', 'prefix': '10.1016'}
{'DOI': '10.1016/j.jneumeth.2009.08.017', 'prefix': '10.1016'}
{'DOI': '10.1016/j.tetlet.2016.05.058', 'prefix': '10.1016'}
{'DOI': '10.1007/s00170-017-0689-z', 'prefix': '10.1007'}
{'DOI': '10.1016/j.dsr.2016.03.004', 'prefix': '10.1016'}
...
Example: 3:
>>> from crossref.restful import Works
>>> works = Works()
>>>: for i in works.filter(has_funder='true', has_license='true') \
.sample(5).select(['DOI', 'prefix']):
>>> print(i)
...
{'DOI': '10.1111/zoj.12146', 'prefix': '10.1093'}
{'DOI': '10.1016/j.bios.2014.04.018', 'prefix': '10.1016}
{'DOI': '10.1016/j.cej.2016.10.011', 'prefix': '10.1016'}
{'DOI': '10.1016/j.dci.2017.08.001', 'prefix': '10.1016'}
{'DOI': '10.1016/j.icheatmasstransfer.2016.09.012', 'prefix': '10.1016'}
...
Example: 4:
>>> from crossref.restful import Works
>>> works = Works()
>>>: for i in works.filter(has_funder='true', has_license='true') \
.sample(5).select('DOI', 'prefix'):
>>> print(i)
...
{'DOI': '10.1111/zoj.12146', 'prefix': '10.1093'}
{'DOI': '10.1016/j.bios.2014.04.018', 'prefix': '10.1016'}
{'DOI': '10.1016/j.cej.2016.10.011', 'prefix': '10.1016'}
{'DOI': '10.1016/j.dci.2017.08.001', 'prefix': '10.1016'}
{'DOI': '10.1016/j.icheatmasstransfer.2016.09.012', 'prefix': '10.1016'}
...
"""
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT, context)
request_params = dict(self.request_params)
select_args = []
invalid_select_args = []
for item in args:
if isinstance(item, list):
select_args += [i.strip() for i in item]
if isinstance(item, str):
select_args += [i.strip() for i in item.split(",")]
invalid_select_args = set(select_args) - set(self.FIELDS_SELECT)
if len(invalid_select_args) != 0:
msg = "Select field's specified as ({}) but must be one of: {}".format(
", ".join(invalid_select_args), ", ".join(self.FIELDS_SELECT))
raise UrlSyntaxError(
msg,
)
request_params["select"] = ",".join(
sorted(
[i for i in set(request_params.get("select", "").split(",") + select_args) if i]),
)
return self.__class__(
request_url=request_url,
request_params=request_params,
context=context,
etiquette=self.etiquette,
timeout=self.timeout,
)
def sort(self, sort="score"):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded with query, filter,
order and facet methods.
kwargs: valid SORT_VALUES arguments.
return: iterable object of Works metadata
Example 1:
>>> from crossref.restful import Works
>>> works = Works()
>>> query = works.sort('deposited')
>>> for item in query:
... print(item['title'])
...
['Integralidade e transdisciplinaridade em ... multiprofissionais na saúde coletiva']
['Aprendizagem em grupo operativo de diabetes: uma abordagem etnográfica']
['A rotatividade de enfermeiros e médicos: ... da Estratégia de Saúde da FamÃlia']
...
Example 2:
>>> from crossref.restful import Works
>>> works = Works()
>>> query = works.sort('relevance')
>>> for item in query:
... print(item['title'])
...
['Proceedings of the American Physical Society']
['Annual Meeting of the Research Society on Alcoholism']
['Local steroid injections: ... hip and on the letter by Swezey']
['Intraventricular neurocytoma']
['Mammography accreditation']
['Temporal lobe necrosis in nasopharyngeal carcinoma: Pictorial essay']
...
"""
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT, context)
request_params = dict(self.request_params)
if sort not in self.SORT_VALUES:
msg = "Sort field specified as {} but must be one of: {}".format(str(sort), ", ".join(
self.SORT_VALUES))
raise UrlSyntaxError(
msg,
)
request_params["sort"] = sort
return self.__class__(
request_url=request_url,
request_params=request_params,
context=context,
etiquette=self.etiquette,
timeout=self.timeout,
)
def filter(self, **kwargs): # noqa: A003
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded and recursively with query, filter,
order, sort and facet methods.
kwargs: valid FILTER_VALIDATOR arguments. Replace `.` with `__` and
`-` with `_` when using parameters.
return: iterable object of Works metadata
Example:
>>> from crossref.restful import Works
>>> works = Works()
>>> query = works.filter(has_funder='true', has_license='true')
>>> for item in query:
... print(item['title'])
...
['Design of smiling-face-shaped band-notched UWB antenna']
['Phase I clinical and pharmacokinetic ... tients with advanced solid tumors']
...
"""
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT, context)
request_params = dict(self.request_params)
for fltr, value in kwargs.items():
decoded_fltr = fltr.replace("__", ".").replace("_", "-")
if decoded_fltr not in self.FILTER_VALIDATOR.keys():
msg = (
f"Filter {decoded_fltr!s} specified but there is no such filter for"
f" this route. Valid filters for this route"
f" are: {', '.join(self.FILTER_VALIDATOR.keys())}"
)
raise UrlSyntaxError(
msg,
)
if self.FILTER_VALIDATOR[decoded_fltr] is not None:
self.FILTER_VALIDATOR[decoded_fltr](str(value))
if "filter" not in request_params:
request_params["filter"] = decoded_fltr + ":" + str(value)
else:
request_params["filter"] += "," + decoded_fltr + ":" + str(value)
return self.__class__(
request_url=request_url,
request_params=request_params,
context=context,
etiquette=self.etiquette,
timeout=self.timeout,
)
def facet(self, facet_name, facet_count=100):
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT, context)
request_params = dict(self.request_params)
request_params["rows"] = 0
if facet_name not in self.FACET_VALUES.keys():
msg = (
f"Facet {facet_name} specified but there is no such facet for this route."
f" Valid facets for this route are: *, affiliation, funder-name, funder-doi,"
f" publisher-name, orcid, container-title, assertion, archive, update-type,"
f" issn, published, source, type-name, license, category-name, relation-type,"
f" assertion-group"
)
raise UrlSyntaxError((
msg
),
", ".join(self.FACET_VALUES.keys()),
)
facet_count = (
self.FACET_VALUES[facet_name]
if self.FACET_VALUES[facet_name] is not None
and self.FACET_VALUES[facet_name] <= facet_count
else facet_count
)
request_params["facet"] = f"{facet_name}:{facet_count}"
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
).json()
return result["message"]["facets"]
def query(self, *args, **kwargs):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded and recursively with query, filter,
order, sort and facet methods.
args: strings (String)
kwargs: valid FIELDS_QUERY arguments.
return: iterable object of Works metadata
Example:
>>> from crossref.restful import Works
>>> works = Works()
>>> query = works.query('Zika Virus')
>>> query.url
'https://api.crossref.org/works?query=Zika+Virus'
>>> for item in query:
... print(item['title'])
...
['Zika Virus']
['Zika virus disease']
['Zika Virus: Laboratory Diagnosis']
['Spread of Zika virus disease']
['Carditis in Zika Virus Infection']
['Understanding Zika virus']
['Zika Virus: History and Infectology']
...
"""
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT, context)
request_params = dict(self.request_params)
if args:
request_params["query"] = " ".join([str(i) for i in args])
for field, value in kwargs.items():
if field not in self.FIELDS_QUERY:
msg = (
f"Field query {field!s} specified but there is no such field query for"
" this route."
f" Valid field queries for this route are: {', '.join(self.FIELDS_QUERY)}"
)
raise UrlSyntaxError(
msg,
)
request_params["query.%s" % field.replace("_", "-")] = value
return self.__class__(request_url=request_url,
request_params=request_params,
context=context,
etiquette=self.etiquette,
timeout=self.timeout)
def sample(self, sample_size=20):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
kwargs: sample_size (Integer) between 0 and 100.
return: iterable object of Works metadata
Example:
>>> from crossref.restful import Works
>>> works = Works()
>>> works.sample(2).url
'https://api.crossref.org/works?sample=2'
>>> [i['title'] for i in works.sample(2)]
[['A study on the hemolytic properties ofPrevotella nigrescens'],
['The geometry and the radial ... of carbon nanotubes: beyond the ideal behaviour']]
"""
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT, context)
request_params = dict(self.request_params)
try:
if sample_size > 100:
msg = (
f"Integer specified as {sample_size!s} but"
" must be a positive integer less than or equal to 100."
)
raise UrlSyntaxError(msg) # noqa: TRY301
except TypeError as exc:
msg = (
f"Integer specified as {sample_size!s} but"
" must be a positive integer less than or equal to 100."
)
raise UrlSyntaxError(msg) from exc
request_params["sample"] = sample_size
return self.__class__(
request_url=request_url,
request_params=request_params,
context=context,
etiquette=self.etiquette,
timeout=self.timeout,
)
def doi(self, doi, only_message=True):
"""
This method retrieve the DOI metadata related to a given DOI
number.
args: Crossref DOI id (String)
return: JSON
Example:
>>> from crossref.restful import Works
>>> works = Works()
>>> works.doi('10.1590/S0004-28032013005000001')
{'is-referenced-by-count': 6, 'reference-count': 216,
'DOI': '10.1590/s0004-28032013005000001',
'subtitle': [], 'issued': {'date-parts': [[2013, 4, 19]]}, 'source': 'Crossref',
'short-container-title': ['Arq. Gastroenterol.'], 'references-count': 216,
'short-title': [],
'deposited': {'timestamp': 1495911725000, 'date-time': '2017-05-27T19:02:05Z',
'date-parts': [[2017, 5, 27]]}, 'ISSN': ['0004-2803'], 'type': 'journal-article',
'URL': 'http://dx.doi.org/10.1590/s0004-28032013005000001',
'indexed': {'timestamp': 1496034748592, 'date-time': '2017-05-29T05:12:28Z',
'date-parts': [[2017, 5, 29]]}, 'content-domain': {'crossmark-restriction': False,
'domain': []},
'created': {'timestamp': 1374613284000, 'date-time': '2013-07-23T21:01:24Z',
'date-parts': [[2013, 7, 23]]}, 'issn-type': [{'value': '0004-2803',
'type': 'electronic'}],
'page': '81-96', 'volume': '50', 'original-title': [], 'subject': ['Gastroenterology'],
'relation': {}, 'container-title': ['Arquivos de Gastroenterologia'], 'member': '530',
'prefix': '10.1590', 'published-print': {'date-parts': [[2013, 4, 19]]},
'title': ['3rd BRAZILIAN CONSENSUS ON Helicobacter pylori'],
'publisher': 'FapUNIFESP (SciELO)', 'alternative-id': ['S0004-28032013000200081'],
'abstract': '<jats:p>Significant abstract data..... .</jats:p>',
'author': [{'affiliation': [{'name': 'Universidade Federal de Minas Gerais, BRAZIL'}],
'family': 'Coelho', 'given': 'Luiz Gonzaga'}, {'affiliation': [
{'name': 'Universidade Federal do Rio Grande do Sul, Brazil'}], 'family': 'Maguinilk',
'given': 'Ismael'}, {'affiliation': [
{'name': 'Presidente de Honra do Núcleo ... para Estudo do Helicobacter, Brazil'}],
'family': 'Zaterka', 'given': 'Schlioma'}, {'affiliation': [
{'name': 'Universidade Federal do PiauÃ, Brasil'}], 'family': 'Parente',
'given': 'José Miguel'},
{'affiliation': [{'name': 'Universidade Federal de Minas Gerais, BRAZIL'}],
'family': 'Passos', 'given': 'Maria do Carmo Friche'}, {'affiliation': [
{'name': 'Universidade de São Paulo, Brasil'}], 'family': 'Moraes-Filho',
'given': 'Joaquim Prado P.'}], 'score': 1.0, 'issue': '2'}
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, doi]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return None
result = result.json()
return result["message"] if only_message is True else result
def agency(self, doi, only_message=True):
"""
This method retrieve the DOI Agency metadata related to a given DOI
number.
args: Crossref DOI id (String)
return: JSON
Example:
>>> from crossref.restful import Works
>>> works = Works()
>>> works.agency('10.1590/S0004-28032013005000001')
{'DOI': '10.1590/s0004-2...5000001', 'agency': {'label': 'CrossRef', 'id': 'crossref'}}
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, doi, "agency"]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return None
result = result.json()
return result["message"] if only_message is True else result
def doi_exists(self, doi):
"""
This method retrieve a boolean according to the existence of a crossref
DOI number. It returns False if the API results a 404 status code.
args: Crossref DOI id (String)
return: Boolean
Example 1:
>>> from crossref.restful import Works
>>> works = Works()
>>> works.doi_exists('10.1590/S0004-28032013005000001')
True
Example 2:
>>> from crossref.restful import Works
>>> works = Works()
>>> works.doi_exists('10.1590/S0004-28032013005000001_invalid_doi')
False
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, doi]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
only_headers=True,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return False
return True
class Funders(Endpoint):
CURSOR_AS_ITER_METHOD = False
ENDPOINT = "funders"
FILTER_VALIDATOR: typing.ClassVar[dict] = {"location": None}
def query(self, *args):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
args: Funder ID (Integer)
return: iterable object of Funders metadata
Example:
>>> from crossref.restful import Funders
>>> funders = Funders()
>>> funders.query('ABBEY').url
'https://api.crossref.org/funders?query=ABBEY'
>>> next(iter(funders.query('ABBEY')))
{'alt-names': ['Abbey'], 'location': 'United Kingdom', 'replaced-by': [],
'replaces': [], 'name': 'ABBEY AWARDS', 'id': '501100000314',
'tokens': ['abbey', 'awards', 'abbey'],
'uri': 'http://dx.doi.org/10.13039/501100000314'}
"""
request_url = build_url_endpoint(self.ENDPOINT)
request_params = dict(self.request_params)
if args:
request_params["query"] = " ".join([str(i) for i in args])
return self.__class__(
request_url=request_url,
request_params=request_params,
etiquette=self.etiquette,
timeout=self.timeout,
)
def filter(self, **kwargs): # noqa: A003
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded and recursively with query, filter,
order, sort and facet methods.
kwargs: valid FILTER_VALIDATOR arguments.
return: iterable object of Funders metadata
Example:
>>> from crossref.restful import Funders
>>> funders = Funders()
>>> query = funders.filter(location='Japan')
>>> for item in query:
... print(item['name'], item['location'])
...
(u'Central Research Institute, Fukuoka University', u'Japan')
(u'Tohoku University', u'Japan')
(u'Information-Technology Promotion Agency', u'Japan')
...
"""
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT, context)
request_params = dict(self.request_params)
for fltr, value in kwargs.items():
decoded_fltr = fltr.replace("__", ".").replace("_", "-")
if decoded_fltr not in self.FILTER_VALIDATOR.keys():
msg = (
f"Filter {decoded_fltr!s} specified but there is no such filter for this route."
f" Valid filters for this route are: {', '.join(self.FILTER_VALIDATOR.keys())}"
)
raise UrlSyntaxError(
msg,
)
if self.FILTER_VALIDATOR[decoded_fltr] is not None:
self.FILTER_VALIDATOR[decoded_fltr](str(value))
if "filter" not in request_params:
request_params["filter"] = decoded_fltr + ":" + str(value)
else:
request_params["filter"] += "," + decoded_fltr + ":" + str(value)
return self.__class__(
request_url=request_url,
request_params=request_params,
context=context,
etiquette=self.etiquette,
timeout=self.timeout,
)
def funder(self, funder_id, only_message=True):
"""
This method retrive a crossref funder metadata related to the
given funder_id.
args: Funder ID (Integer)
Example:
>>> from crossref.restful import Funders
>>> funders = Funders()
>>> funders.funder('501100000314')
{'hierarchy': {'501100000314': {}}, 'alt-names': ['Abbey'],
'work-count': 3, 'replaced-by': [], 'replaces': [],
'hierarchy-names': {'501100000314': 'ABBEY AWARDS'},
'uri': 'http://dx.doi.org/10.13039/501100000314', 'location': 'United Kingdom',
'descendant-work-count': 3, 'descendants': [], 'name': 'ABBEY AWARDS',
'id': '501100000314', 'tokens': ['abbey', 'awards', 'abbey']}
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, str(funder_id)]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return None
result = result.json()
return result["message"] if only_message is True else result
def funder_exists(self, funder_id):
"""
This method retrieve a boolean according to the existence of a crossref
funder. It returns False if the API results a 404 status code.
args: Crossref Funder id (Integer)
return: Boolean
Example 1:
>>> from crossref.restful import Funders
>>> funders = Funders()
>>> funders.funder_exists('501100000314')
True
Example 2:
>>> from crossref.restful import Funders
>>> funders = Funders()
>>> funders.funder_exists('999999999999')
False
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, str(funder_id)]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
only_headers=True,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return False
return True
def works(self, funder_id):
"""
This method retrieve a iterable of Works of the given funder.
args: Crossref allowed document Types (String)
return: Works()
"""
context = f"{self.ENDPOINT}/{funder_id!s}"
return Works(context=context)
class Members(Endpoint):
CURSOR_AS_ITER_METHOD = False
ENDPOINT = "members"
FILTER_VALIDATOR: typing.ClassVar[dict] = {
"prefix": None,
"has-public-references": validators.is_bool,
"backfile-doi-count": validators.is_integer,
"current-doi-count": validators.is_integer,
}
def query(self, *args):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
args: strings (String)
return: iterable object of Members metadata
Example:
>>> from crossref.restful import Members
>>> members = Members().query('Korean Association')
members.query('Korean Association').url
'https://api.crossref.org/journals?query=Public+Health+Health+Science'
>>> next(iter(members.query('Korean Association')))
{'prefix': [{'value': '10.20433', 'public-references': False,
'name': 'The New Korean Philosophical Association'}],
'counts': {'total-dois': 0, 'backfile-dois': 0,
'current-dois': 0}, 'coverage': {'references-backfile': 0, 'references-current': 0,
'abstracts-current': 0, 'update-policies-backfile': 0, 'orcids-current': 0,
'orcids-backfile': 0,
'licenses-current': 0, 'affiliations-backfile': 0, 'licenses-backfile': 0,
'update-policies-current': 0,
'resource-links-current': 0, 'resource-links-backfile': 0, 'award-numbers-backfile': 0,
'abstracts-backfile': 0, 'funders-current': 0, 'funders-backfile': 0,
'affiliations-current': 0,
'award-numbers-current': 0}, 'flags': {'deposits-orcids-backfile': False,
'deposits-references-backfile': False, 'deposits-licenses-current': False,
'deposits': False,
'deposits-abstracts-current': False, 'deposits-award-numbers-current': False,
'deposits-articles': False,
'deposits-resource-links-backfile': False, 'deposits-funders-current': False,
'deposits-award-numbers-backfile': False, 'deposits-references-current': False,
'deposits-abstracts-backfile': False, 'deposits-funders-backfile': False,
'deposits-update-policies-current': False, 'deposits-orcids-current': False,
'deposits-licenses-backfile': False, 'deposits-affiliations-backfile': False,
'deposits-update-policies-backfile': False, 'deposits-resource-links-current': False,
'deposits-affiliations-current': False}, 'names': ['The New Korean ... Association'],
'breakdowns': {'dois-by-issued-year': []}, 'location': 'Dongsin Tow ... llae-dong 6-ga,
Mullae-dong 6-ga Seoul 150-096 South Korea', 'prefixes': ['10.20433'],
'last-status-check-time': 1496034177684, 'id': 8334,
'tokens': ['the', 'new', 'korean', 'philosophical',
'association'], 'primary-name': 'The New Korean Philosophical Association'}
"""
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT)
request_params = dict(self.request_params)
if args:
request_params["query"] = " ".join([str(i) for i in args])
return self.__class__(
request_url=request_url,
request_params=request_params,
context=context,
etiquette=self.etiquette,
timeout=self.timeout,
)
def filter(self, **kwargs): # noqa: A003
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded and recursively with query, filter,
order, sort and facet methods.
kwargs: valid FILTER_VALIDATOR arguments.
return: iterable object of Members metadata
Example:
>>> from crossref.restful import Members
>>> members = Members()
>>> query = members.filter(has_public_references='true')
>>> for item in query:
... print(item['prefix'])
...
[
{u'public-references': False, u'name': u'Open Library of Humanities',
u'value': u'10.16995'},
{u'public-references': True, u'name': u'Martin Eve', u'value': u'10.7766'}
]
[
{u'public-references': True, u'name': u'Institute of Business Research',
u'value': u'10.24122'}
]
...
"""
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT, context)
request_params = dict(self.request_params)
for fltr, value in kwargs.items():
decoded_fltr = fltr.replace("__", ".").replace("_", "-")
if decoded_fltr not in self.FILTER_VALIDATOR.keys():
msg = (
f"Filter {decoded_fltr!s} specified but there is no such filter for this route."
f" Valid filters for this route are: {', '.join(self.FILTER_VALIDATOR.keys())}"
)
raise UrlSyntaxError(msg)
if self.FILTER_VALIDATOR[decoded_fltr] is not None:
self.FILTER_VALIDATOR[decoded_fltr](str(value))
if "filter" not in request_params:
request_params["filter"] = decoded_fltr + ":" + str(value)
else:
request_params["filter"] += "," + decoded_fltr + ":" + str(value)
return self.__class__(
request_url=request_url,
request_params=request_params,
context=context,
etiquette=self.etiquette,
timeout=self.timeout,
)
def member(self, member_id, only_message=True):
"""
This method retrive a crossref member metadata related to the
given member_id.
args: Member ID (Integer)
Example:
>>> from crossref.restful import Members
>>> members = Members()
>>> members.member(101)
{'prefix': [{'value': '10.1024', 'public-references': False,
'name': 'Hogrefe Publishing Group'}, {'value': '10.1027', 'public-references': False,
'name': 'Hogrefe Publishing Group'}, {'value': '10.1026', 'public-references': False,
'name': 'Hogrefe Publishing Group'}], 'counts': {'total-dois': 35039,
'backfile-dois': 31430,
'current-dois': 3609}, 'coverage': {'references-backfile': 0.3601972758769989,
'references-current': 0.019118869677186012, 'abstracts-current': 0.0,
'update-policies-backfile': 0.0, 'orcids-current': 0.0, 'orcids-backfile': 0.0,
'licenses-current': 0.0, 'affiliations-backfile': 0.05685650557279587,
'licenses-backfile': 0.0, 'update-policies-current': 0.0, 'resource-links-current': 0.0,
'resource-links-backfile': 0.0, 'award-numbers-backfile': 0.0,
'abstracts-backfile': 0.0,
'funders-current': 0.0, 'funders-backfile': 0.0,
'affiliations-current': 0.15710723400115967,
'award-numbers-current': 0.0}, 'flags': {'deposits-orcids-backfile': False,
'deposits-references-backfile': True, 'deposits-licenses-current': False,
'deposits': True,
'deposits-abstracts-current': False, 'deposits-award-numbers-current': False,
'deposits-articles': True, 'deposits-resource-links-backfile': False,
'deposits-funders-current': False, 'deposits-award-numbers-backfile': False,
'deposits-references-current': True, 'deposits-abstracts-backfile': False,
'deposits-funders-backfile': False, 'deposits-update-policies-current': False,
'deposits-orcids-current': False, 'deposits-licenses-backfile': False,
'deposits-affiliations-backfile': True, 'deposits-update-policies-backfile': False,
'deposits-resource-links-current': False, 'deposits-affiliations-current': True},
'names': ['Hogrefe Publishing Group'], 'breakdowns': {'dois-by-issued-year':
[[2003, 2329], [2004, 2264], [2002, 2211], [2005, 2204], [2006, 2158],
[2007, 2121], [2016, 1954],
[2008, 1884], [2015, 1838], [2012, 1827], [2013, 1805], [2014, 1796],
[2009, 1760], [2010, 1718],
[2011, 1681], [2001, 1479], [2000, 1477], [1999, 1267], [2017, 767],
[1997, 164], [1996, 140],
[1998, 138], [1995, 103], [1994, 11], [1993, 11], [0, 1]]},
'location': 'Langgass-Strasse 76 Berne CH-3000 Switzerland', 'prefixes':
['10.1024', '10.1027',
'10.1026'], 'last-status-check-time': 1496034132646, 'id': 101, 'tokens':
['hogrefe', 'publishing',
'group'], 'primary-name': 'Hogrefe Publishing Group'}
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, str(member_id)]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return None
result = result.json()
return result["message"] if only_message is True else result
def member_exists(self, member_id):
"""
This method retrieve a boolean according to the existence of a crossref
member. It returns False if the API results a 404 status code.
args: Crossref allowed document Type (String)
return: Boolean
Example 1:
>>> from crossref.restful import Members
>>> members = Members()
>>> members.member_exists(101)
True
Example 2:
>>> from crossref.restful import Members
>>> members = Members()
>>> members.member_exists(88888)
False
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, str(member_id)]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
only_headers=True,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return False
return True
def works(self, member_id):
"""
This method retrieve a iterable of Works of the given member.
args: Member ID (Integer)
return: Works()
"""
context = f"{self.ENDPOINT}/{member_id!s}"
return Works(context=context)
class Types(Endpoint):
CURSOR_AS_ITER_METHOD = False
ENDPOINT = "types"
def type(self, type_id, only_message=True): # noqa: A003
"""
This method retrive a crossref document type metadata related to the
given type_id.
args: Crossref allowed document Types (String)
Example:
>>> types.type('journal-article')
{'label': 'Journal Article', 'id': 'journal-article'}
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, str(type_id)]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return None
result = result.json()
return result["message"] if only_message is True else result
def all(self): # noqa: A003
"""
This method retrieve an iterator with all the available types.
return: iterator of crossref document types
Example:
>>> from crossref.restful import Types
>>> types = Types()
>>> [i for i in types.all()]
[{'label': 'Book Section', 'id': 'book-section'},
{'label': 'Monograph', 'id': 'monograph'},
{'label': 'Report', 'id': 'report'},
{'label': 'Book Track', 'id': 'book-track'},
{'label': 'Journal Article', 'id': 'journal-article'},
{'label': 'Part', 'id': 'book-part'},
...
}]
"""
request_url = build_url_endpoint(self.ENDPOINT, self.context)
request_params = dict(self.request_params)
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return
result = result.json()
yield from result["message"]["items"]
def type_exists(self, type_id):
"""
This method retrieve a boolean according to the existence of a crossref
document type. It returns False if the API results a 404 status code.
args: Crossref allowed document Type (String)
return: Boolean
Example 1:
>>> from crossref.restful import Types
>>> types = Types()
>>> types.type_exists('journal-article')
True
Example 2:
>>> from crossref.restful import Types
>>> types = Types()
>>> types.type_exists('unavailable type')
False
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, str(type_id)]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
only_headers=True,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return False
return True
def works(self, type_id):
"""
This method retrieve a iterable of Works of the given type.
args: Crossref allowed document Types (String)
return: Works()
"""
context = f"{self.ENDPOINT}/{type_id!s}"
return Works(context=context)
class Prefixes(Endpoint):
CURSOR_AS_ITER_METHOD = False
ENDPOINT = "prefixes"
def prefix(self, prefix_id, only_message=True):
"""
This method retrieve a json with the given Prefix metadata
args: Crossref Prefix (String)
return: JSON
Example:
>>> from crossref.restful import Prefixes
>>> prefixes = Prefixes()
>>> prefixes.prefix('10.1590')
{'name': 'FapUNIFESP (SciELO)', 'member': 'http://id.crossref.org/member/530',
'prefix': 'http://id.crossref.org/prefix/10.1590'}
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, str(prefix_id)]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return None
result = result.json()
return result["message"] if only_message is True else result
def works(self, prefix_id):
"""
This method retrieve a iterable of Works of the given prefix.
args: Crossref Prefix (String)
return: Works()
"""
context = f"{self.ENDPOINT}/{prefix_id!s}"
return Works(context=context)
class Journals(Endpoint):
CURSOR_AS_ITER_METHOD = False
ENDPOINT = "journals"
def query(self, *args):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
args: strings (String)
return: iterable object of Journals metadata
Example:
>>> from crossref.restful import Journals
>>> journals = Journals().query('Public Health', 'Health Science')
>>> journals.url
'https://api.crossref.org/journals?query=Public+Health+Health+Science'
>>> next(iter(journals))
{'last-status-check-time': None, 'counts': None, 'coverage': None,
'publisher': 'ScopeMed International Medical Journal Managment and Indexing System',
'flags': None, 'breakdowns': None, 'ISSN': ['2320-4664', '2277-338X'],
'title': 'International Journal of Medical Science and Public Health'}
"""
context = str(self.context)
request_url = build_url_endpoint(self.ENDPOINT)
request_params = dict(self.request_params)
if args:
request_params["query"] = " ".join([str(i) for i in args])
return self.__class__(
request_url=request_url,
request_params=request_params,
context=context,
etiquette=self.etiquette,
timeout=self.timeout,
)
def journal(self, issn, only_message=True):
"""
This method retrieve a json with the given ISSN metadata
args: Journal ISSN (String)
return: Journal JSON data
Example:
>>> from crossref.restful import Journals
>>> journals = Journals()
>>> journals.journal('2277-338X')
{'last-status-check-time': None, 'counts': None, 'coverage': None,
'publisher': 'ScopeMed International Medical Journal Managment and Indexing System',
'flags': None, 'breakdowns': None, 'ISSN': ['2320-4664', '2277-338X'],
'title': 'International Journal of Medical Science and Public Health'}
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, str(issn)]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return None
result = result.json()
return result["message"] if only_message is True else result
def journal_exists(self, issn):
"""
This method retrieve a boolean according to the existence of a journal
in the Crossref database. It returns False if the API results a 404
status code.
args: Journal ISSN (String)
return: Boolean
Example 1:
>>> from crossref.restful import Journals
>>> journals = Journals()
>>> journals.journal_exists('2277-338X')
True
Example 2:
>>> from crossref.restful import Journals
>>> journals = Journals()
>>> journals.journal_exists('9999-AAAA')
False
"""
request_url = build_url_endpoint("/".join([self.ENDPOINT, str(issn)]))
request_params = {}
result = self.do_http_request(
"get",
request_url,
data=request_params,
only_headers=True,
custom_header=self.custom_header,
timeout=self.timeout,
)
if result.status_code == 404:
return False
return True
def works(self, issn):
"""
This method retrieve a iterable of Works of the given journal.
args: Journal ISSN (String)
return: Works()
"""
context = f"{self.ENDPOINT}/{issn!s}"
return Works(context=context)
class Depositor:
def __init__( # noqa: PLR0913
self, prefix, api_user, api_key, etiquette=None, use_test_server=False, timeout=100,
):
self.do_http_request = HTTPRequest(throttle=False).do_http_request
self.etiquette = etiquette or Etiquette()
self.custom_header = {"user-agent": str(self.etiquette)}
self.prefix = prefix
self.api_user = api_user
self.api_key = api_key
self.use_test_server = use_test_server
self.timeout = timeout
def get_endpoint(self, verb):
subdomain = "test" if self.use_test_server else "doi"
return f"https://{subdomain}.crossref.org/servlet/{verb}"
def register_doi(self, submission_id, request_xml):
"""
This method registry a new DOI number in Crossref or update some DOI
metadata.
submission_id: Will be used as the submission file name. The file name
could be used in future requests to retrieve the submission status.
request_xml: The XML with the document metadata. It must be under
compliance with the Crossref Submission Schema.
"""
endpoint = self.get_endpoint("deposit")
files = {"mdFile": ("%s.xml" % submission_id, request_xml)}
params = {
"operation": "doMDUpload",
"login_id": self.api_user,
"login_passwd": self.api_key,
}
return self.do_http_request(
"post",
endpoint,
data=params,
files=files,
custom_header=self.custom_header,
timeout=self.timeout,
)
def request_doi_status_by_filename(self, file_name, data_type="result"):
"""
This method retrieve the DOI requests status.
file_name: Used as unique ID to identify a deposit.
data_type: [contents, result]
contents - retrieve the XML submited by the publisher
result - retrieve a JSON with the status of the submission
"""
endpoint = self.get_endpoint("submissionDownload")
params = {
"usr": self.api_user,
"pwd": self.api_key,
"file_name": file_name,
"type": data_type,
}
return self.do_http_request(
"get", endpoint, data=params, custom_header=self.custom_header, timeout=self.timeout,
)
def request_doi_status_by_batch_id(self, doi_batch_id, data_type="result"):
"""
This method retrieve the DOI requests status.
file_name: Used as unique ID to identify a deposit.
data_type: [contents, result]
contents - retrieve the XML submited by the publisher
result - retrieve a XML with the status of the submission
"""
endpoint = self.get_endpoint("submissionDownload")
params = {
"usr": self.api_user,
"pwd": self.api_key,
"doi_batch_id": doi_batch_id,
"type": data_type,
}
return self.do_http_request(
"get", endpoint, data=params, custom_header=self.custom_header, timeout=self.timeout,
)
|