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 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691
|
"""Dataverse API wrapper for all it's API's."""
import json
from typing import Any, Dict, Optional
import httpx
import subprocess as sp
from warnings import warn
from httpx import ConnectError, Response
from pyDataverse.auth import ApiTokenAuth
from pyDataverse.exceptions import (
ApiAuthorizationError,
ApiUrlError,
DatasetNotFoundError,
DataverseNotEmptyError,
DataverseNotFoundError,
OperationFailedError,
)
DEPRECATION_GUARD = object()
class Api:
"""Base class.
Parameters
----------
base_url : str
Base URL of Dataverse instance. Without trailing `/` at the end.
e.g. `http://demo.dataverse.org`
api_token : str
Authentication token for the api.
Attributes
----------
base_url
api_token
dataverse_version
"""
def __init__(
self,
base_url: str,
api_token: Optional[str] = None,
api_version: str = "latest",
*,
auth: Optional[httpx.Auth] = None,
):
"""Init an Api() class.
Scheme, host and path combined create the base-url for the api.
See more about URL at `Wikipedia <https://en.wikipedia.org/wiki/URL>`_.
Parameters
----------
base_url : str
Base url for Dataverse api.
api_token : str | None
API token for Dataverse API. If you provide an :code:`api_token`, we
assume it is an API token as retrieved via your Dataverse instance
user profile.
We recommend using the :code:`auth` argument instead.
To retain the current behaviour with the :code:`auth` argument, change
.. code-block:: python
Api("https://demo.dataverse.org", "my_token")
to
.. code-block:: python
from pyDataverse.auth import ApiTokenAuth
Api("https://demo.dataverse.org", auth=ApiTokenAuth("my_token"))
If you are using an OIDC/OAuth 2.0 Bearer token, please use the :code:`auth`
parameter with the :py:class:`.auth.BearerTokenAuth`.
api_version : str
The version string of the Dataverse API or :code:`latest`, e.g.,
:code:`v1`. Defaults to :code:`latest`, which drops the version from
the API urls.
auth : httpx.Auth | None
You can provide any authentication mechanism you like to connect to
your Dataverse instance. The most common mechanisms are implemented
in :py:mod:`.auth`, but if one is missing, you can use your own
`httpx.Auth`-compatible class. For more information, have a look at
`httpx' Authentication docs
<https://www.python-httpx.org/advanced/authentication/>`_.
Examples
-------
Create an API connection::
.. code-block::
>>> from pyDataverse.api import Api
>>> base_url = 'http://demo.dataverse.org'
>>> api = Api(base_url)
.. code-block::
>>> from pyDataverse.api import Api
>>> from pyDataverse.auth import ApiTokenAuth
>>> base_url = 'http://demo.dataverse.org'
>>> api = Api(base_url, ApiTokenAuth('my_api_token'))
"""
if not isinstance(base_url, str):
raise ApiUrlError("base_url {0} is not a string.".format(base_url))
self.base_url = base_url.rstrip("/")
self.client = None
if not isinstance(api_version, str):
raise ApiUrlError("api_version {0} is not a string.".format(api_version))
self.api_version = api_version
self.auth = auth
self.api_token = api_token
if api_token is not None:
if auth is None:
self.auth = ApiTokenAuth(api_token)
else:
self.api_token = None
warn(
UserWarning(
"You provided both, an api_token and a custom auth "
"method. We will only use the auth method."
)
)
if self.api_version == "latest":
self.base_url_api = "{0}/api".format(self.base_url)
else:
self.base_url_api = "{0}/api/{1}".format(self.base_url, self.api_version)
self.timeout = 500
def __str__(self):
"""Return the class name and URL of the used API class.
Returns
-------
str
Naming of the API class.
"""
return f"{self.__class__.__name__}: {self.base_url_api}"
def get_request(self, url, params=None, auth=DEPRECATION_GUARD):
"""Make a GET request.
Parameters
----------
url : str
Full URL.
params : dict
Dictionary of parameters to be passed with the request.
Defaults to `None`.
auth : Any
.. deprecated:: 0.3.4
The auth parameter was ignored before version 0.3.4.
Please pass your auth to the Api instance directly, as
explained in :py:func:`Api.__init__`.
If you need multiple auth methods, create multiple
API instances:
.. code-block:: python
api = Api("https://demo.dataverse.org", auth=ApiTokenAuth("my_api_token"))
api_oauth = Api("https://demo.dataverse.org", auth=BearerTokenAuth("my_bearer_token"))
Returns
-------
httpx.Response
Response object of httpx library.
"""
if auth is not DEPRECATION_GUARD:
warn(
DeprecationWarning(
"The auth parameter is deprecated. Please pass your auth "
"arguments to the __init__ method instead."
)
)
headers = {}
headers["User-Agent"] = "pydataverse"
if self.client is None:
return self._sync_request(
method=httpx.get,
url=url,
headers=headers,
params=params,
)
else:
return self._async_request(
method=self.client.get,
url=url,
headers=headers,
params=params,
)
def post_request(
self, url, data=None, auth=DEPRECATION_GUARD, params=None, files=None
):
"""Make a POST request.
params will be added as key-value pairs to the URL.
Parameters
----------
url : str
Full URL.
data : str
Metadata as a json-formatted string. Defaults to `None`.
auth : Any
.. deprecated:: 0.3.4
The auth parameter was ignored before version 0.3.4.
Please pass your auth to the Api instance directly, as
explained in :py:func:`Api.__init__`.
If you need multiple auth methods, create multiple
API instances:
.. code-block:: python
api = Api("https://demo.dataverse.org", auth=ApiTokenAuth("my_api_token"))
api_oauth = Api("https://demo.dataverse.org", auth=BearerTokenAuth("my_bearer_token"))
files : dict
e.g. :code:`files={'file': open('sample_file.txt','rb')}`
params : dict
Dictionary of parameters to be passed with the request.
Defaults to :code:`None`.
Returns
-------
httpx.Response
Response object of httpx library.
"""
if auth is not DEPRECATION_GUARD:
warn(
DeprecationWarning(
"The auth parameter is deprecated. Please pass your auth "
"arguments to the __init__ method instead."
)
)
headers = {}
headers["User-Agent"] = "pydataverse"
if isinstance(data, str):
data = json.loads(data)
# Decide whether to use 'data' or 'json' args
request_params = self._check_json_data_form(data)
if self.client is None:
return self._sync_request(
method=httpx.post,
url=url,
headers=headers,
params=params,
files=files,
**request_params,
)
else:
return self._async_request(
method=self.client.post,
url=url,
headers=headers,
params=params,
files=files,
**request_params,
)
def put_request(self, url, data=None, auth=DEPRECATION_GUARD, params=None):
"""Make a PUT request.
Parameters
----------
url : str
Full URL.
data : str
Metadata as a json-formatted string. Defaults to `None`.
auth : Any
.. deprecated:: 0.3.4
The auth parameter was ignored before version 0.3.4.
Please pass your auth to the Api instance directly, as
explained in :py:func:`Api.__init__`.
If you need multiple auth methods, create multiple
API instances:
.. code-block:: python
api = Api("https://demo.dataverse.org", auth=ApiTokenAuth("my_api_token"))
api_oauth = Api("https://demo.dataverse.org", auth=BearerTokenAuth("my_bearer_token"))
params : dict
Dictionary of parameters to be passed with the request.
Defaults to `None`.
Returns
-------
httpx.Response
Response object of httpx library.
"""
if auth is not DEPRECATION_GUARD:
warn(
DeprecationWarning(
"The auth parameter is deprecated. Please pass your auth "
"arguments to the __init__ method instead."
)
)
headers = {}
headers["User-Agent"] = "pydataverse"
if isinstance(data, str):
data = json.loads(data)
# Decide whether to use 'data' or 'json' args
request_params = self._check_json_data_form(data)
if self.client is None:
return self._sync_request(
method=httpx.put,
url=url,
json=data,
headers=headers,
params=params,
**request_params,
)
else:
return self._async_request(
method=self.client.put,
url=url,
json=data,
headers=headers,
params=params,
**request_params,
)
def delete_request(self, url, auth=DEPRECATION_GUARD, params=None):
"""Make a Delete request.
Parameters
----------
url : str
Full URL.
auth : Any
.. deprecated:: 0.3.4
The auth parameter was ignored before version 0.3.4.
Please pass your auth to the Api instance directly, as
explained in :py:func:`Api.__init__`.
If you need multiple auth methods, create multiple
API instances:
.. code-block:: python
api = Api("https://demo.dataverse.org", auth=ApiTokenAuth("my_api_token"))
api_oauth = Api("https://demo.dataverse.org", auth=BearerTokenAuth("my_bearer_token"))
params : dict
Dictionary of parameters to be passed with the request.
Defaults to `None`.
Returns
-------
httpx.Response
Response object of httpx library.
"""
if auth is not DEPRECATION_GUARD:
warn(
DeprecationWarning(
"The auth parameter is deprecated. Please pass your auth "
"arguments to the __init__ method instead."
)
)
headers = {}
headers["User-Agent"] = "pydataverse"
if self.client is None:
return self._sync_request(
method=httpx.delete,
url=url,
headers=headers,
params=params,
)
else:
return self._async_request(
method=self.client.delete,
url=url,
headers=headers,
params=params,
)
@staticmethod
def _check_json_data_form(data: Optional[Dict]):
"""This method checks and distributes given payload to match Dataverse expectations.
In the case of the form-data keyed by "jsonData", Dataverse expects
the payload as a string in a form of a dictionary. This is not possible
using HTTPXs json parameter, so we need to handle this case separately.
"""
if not data:
return {}
elif not isinstance(data, dict):
raise ValueError("Data must be a dictionary.")
elif "jsonData" not in data:
return {"json": data}
assert list(data.keys()) == [
"jsonData"
], "jsonData must be the only key in the dictionary."
# Content of JSON data should ideally be a string
content = data["jsonData"]
if not isinstance(content, str):
data["jsonData"] = json.dumps(content)
return {"data": data}
def _sync_request(
self,
method,
**kwargs,
):
"""
Sends a synchronous request to the specified URL using the specified HTTP method.
Args:
method (function): The HTTP method to use for the request.
**kwargs: Additional keyword arguments to be passed to the method.
Returns:
httpx.Response: The response object returned by the request.
Raises:
ApiAuthorizationError: If the response status code is 401 (Authorization error).
ConnectError: If a connection to the API cannot be established.
"""
assert "url" in kwargs, "URL is required for a request."
kwargs = self._filter_kwargs(kwargs)
try:
resp: httpx.Response = method(
**kwargs, auth=self.auth, follow_redirects=True, timeout=None
)
if resp.status_code == 401:
try:
error_msg = resp.json()["message"]
except json.JSONDecodeError:
error_msg = resp.reason_phrase
raise ApiAuthorizationError(
"ERROR: HTTP 401 - Authorization error {0}. MSG: {1}".format(
kwargs["url"], error_msg
)
)
return resp
except ConnectError:
raise ConnectError(
"ERROR - Could not establish connection to api '{0}'.".format(
kwargs["url"]
)
)
async def _async_request(
self,
method,
**kwargs,
):
"""
Sends an asynchronous request to the specified URL using the specified HTTP method.
Args:
method (callable): The HTTP method to use for the request.
**kwargs: Additional keyword arguments to be passed to the method.
Raises:
ApiAuthorizationError: If the response status code is 401 (Authorization error).
ConnectError: If a connection to the API cannot be established.
Returns:
The response object.
"""
assert "url" in kwargs, "URL is required for a request."
kwargs = self._filter_kwargs(kwargs)
try:
resp = await method(**kwargs, auth=self.auth)
if resp.status_code == 401:
error_msg = resp.json()["message"]
raise ApiAuthorizationError(
"ERROR: HTTP 401 - Authorization error {0}. MSG: {1}".format(
kwargs["url"], error_msg
)
)
return resp
except ConnectError:
raise ConnectError(
"ERROR - Could not establish connection to api '{0}'.".format(
kwargs["url"]
)
)
@staticmethod
def _filter_kwargs(kwargs: Dict[str, Any]) -> Dict[str, Any]:
"""
Filters out any keyword arguments that are `None` from the specified dictionary.
Args:
kwargs (Dict[str, Any]): The dictionary to filter.
Returns:
Dict[str, Any]: The filtered dictionary.
"""
return {k: v for k, v in kwargs.items() if v is not None}
async def __aenter__(self):
"""
Context manager method that initializes an instance of httpx.AsyncClient.
Returns:
httpx.AsyncClient: An instance of httpx.AsyncClient.
"""
self.client = httpx.AsyncClient()
async def __aexit__(self, exc_type, exc_value, traceback):
"""
Closes the client connection when exiting a context manager.
Args:
exc_type (type): The type of the exception raised, if any.
exc_value (Exception): The exception raised, if any.
traceback (traceback): The traceback object associated with the exception, if any.
"""
await self.client.aclose()
self.client = None
class DataAccessApi(Api):
"""Class to access Dataverse's Data Access API.
Attributes
----------
base_url_api_data_access : type
Description of attribute `base_url_api_data_access`.
base_url : type
Description of attribute `base_url`.
"""
def __init__(self, base_url, api_token=None, *, auth=None):
"""Init an DataAccessApi() class."""
super().__init__(base_url, api_token, auth=auth)
if base_url:
self.base_url_api_data_access = "{0}/access".format(self.base_url_api)
else:
self.base_url_api_data_access = self.base_url_api
def get_datafile(
self,
identifier,
data_format=None,
no_var_header=None,
image_thumb=None,
is_pid=True,
auth=DEPRECATION_GUARD,
):
"""Download a datafile via the Dataverse Data Access API.
Get by file id (HTTP Request).
.. code-block:: bash
GET /api/access/datafile/$id
Get by persistent identifier (HTTP Request).
.. code-block:: bash
GET http://$SERVER/api/access/datafile/:persistentId/?persistentId=doi:10.5072/FK2/J8SJZB
Parameters
----------
identifier : str
Identifier of the datafile. Can be datafile id or persistent
identifier of the datafile (e. g. doi).
is_pid : bool
``True`` to use persistent identifier. ``False``, if not.
Returns
-------
httpx.Response
Response object of httpx library.
"""
is_first_param = True
if is_pid:
url = "{0}/datafile/:persistentId/?persistentId={1}".format(
self.base_url_api_data_access, identifier
)
else:
url = "{0}/datafile/{1}".format(self.base_url_api_data_access, identifier)
if data_format or no_var_header or image_thumb:
url += "?"
if data_format:
url += "format={0}".format(data_format)
is_first_param = False
if no_var_header:
if not is_first_param:
url += "&"
url += "noVarHeader={0}".format(no_var_header)
is_first_param = False
if image_thumb:
if not is_first_param:
url += "&"
url += "imageThumb={0}".format(image_thumb)
return self.get_request(url, auth=auth)
def get_datafiles(self, identifier, data_format=None, auth=DEPRECATION_GUARD):
"""Download a datafile via the Dataverse Data Access API.
Get by file id (HTTP Request).
.. code-block:: bash
GET /api/access/datafiles/$id1,$id2,...$idN
Get by persistent identifier (HTTP Request).
Parameters
----------
identifier : str
Identifier of the dataset. Can be datafile id or persistent
identifier of the datafile (e. g. doi).
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/datafiles/{1}".format(self.base_url_api_data_access, identifier)
if data_format:
url += "?format={0}".format(data_format)
return self.get_request(url, auth=auth)
def get_datafile_bundle(
self, identifier, file_metadata_id=None, auth=DEPRECATION_GUARD
):
"""Download a datafile in all its formats.
HTTP Request:
.. code-block:: bash
GET /api/access/datafile/bundle/$id
Data Access API calls can now be made using persistent identifiers (in
addition to database ids). This is done by passing the constant
:persistentId where the numeric id of the file is expected, and then
passing the actual persistent id as a query parameter with the name
persistentId.
This is a convenience packaging method available for tabular data
files. It returns a zipped bundle that contains the data in the
following formats:
- Tab-delimited;
- “Saved Original”, the proprietary (SPSS, Stata, R, etc.) file
from which the tabular data was ingested;
- Generated R Data frame (unless the “original” above was in R);
- Data (Variable) metadata record, in DDI XML;
- File citation, in Endnote and RIS formats.
Parameters
----------
identifier : str
Identifier of the dataset.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/datafile/bundle/{1}".format(
self.base_url_api_data_access, identifier
)
if file_metadata_id:
url += "?fileMetadataId={0}".format(file_metadata_id)
return self.get_request(url, auth=auth)
def request_access(self, identifier, auth=DEPRECATION_GUARD, is_filepid=False):
"""Request datafile access.
This method requests access to the datafile whose id is passed on the behalf of an authenticated user whose key is passed. Note that not all datasets allow access requests to restricted files.
https://guides.dataverse.org/en/4.18.1/api/dataaccess.html#request-access
/api/access/datafile/$id/requestAccess
curl -H "X-Dataverse-key:$API_TOKEN" -X PUT http://$SERVER/api/access/datafile/{id}/requestAccess
"""
if is_filepid:
url = "{0}/datafile/:persistentId/requestAccess?persistentId={1}".format(
self.base_url_api_data_access, identifier
)
else:
url = "{0}/datafile/{1}/requestAccess".format(
self.base_url_api_data_access, identifier
)
return self.put_request(url, auth=auth)
def allow_access_request(
self, identifier, do_allow=True, auth=DEPRECATION_GUARD, is_pid=True
):
"""Allow access request for datafiles.
https://guides.dataverse.org/en/latest/api/dataaccess.html#allow-access-requests
curl -H "X-Dataverse-key:$API_TOKEN" -X PUT -d true http://$SERVER/api/access/{id}/allowAccessRequest
curl -H "X-Dataverse-key:$API_TOKEN" -X PUT -d true http://$SERVER/api/access/:persistentId/allowAccessRequest?persistentId={pid}
"""
if is_pid:
url = "{0}/:persistentId/allowAccessRequest?persistentId={1}".format(
self.base_url_api_data_access, identifier
)
else:
url = "{0}/{1}/allowAccessRequest".format(
self.base_url_api_data_access, identifier
)
if do_allow:
data = "true"
else:
data = "false"
return self.put_request(url, data=data, auth=auth)
def grant_file_access(self, identifier, user, auth=DEPRECATION_GUARD):
"""Grant datafile access.
https://guides.dataverse.org/en/4.18.1/api/dataaccess.html#grant-file-access
curl -H "X-Dataverse-key:$API_TOKEN" -X PUT http://$SERVER/api/access/datafile/{id}/grantAccess/{@userIdentifier}
"""
url = "{0}/datafile/{1}/grantAccess/{2}".format(
self.base_url_api_data_access, identifier, user
)
return self.put_request(url, auth=auth)
def list_file_access_requests(self, identifier, auth=DEPRECATION_GUARD):
"""Liste datafile access requests.
https://guides.dataverse.org/en/4.18.1/api/dataaccess.html#list-file-access-requests
curl -H "X-Dataverse-key:$API_TOKEN" -X GET http://$SERVER/api/access/datafile/{id}/listRequests
"""
url = "{0}/datafile/{1}/listRequests".format(
self.base_url_api_data_access, identifier
)
return self.get_request(url, auth=auth)
class MetricsApi(Api):
"""Class to access Dataverse's Metrics API.
Attributes
----------
base_url_api_metrics : type
Description of attribute `base_url_api_metrics`.
base_url : type
Description of attribute `base_url`.
"""
def __init__(self, base_url, api_token=None, api_version="latest", *, auth=None):
"""Init an MetricsApi() class."""
super().__init__(base_url, api_token, api_version, auth=auth)
if base_url:
self.base_url_api_metrics = "{0}/api/info/metrics".format(self.base_url)
else:
self.base_url_api_metrics = None
def total(self, data_type, date_str=None, auth=DEPRECATION_GUARD):
"""
GET https://$SERVER/api/info/metrics/$type
GET https://$SERVER/api/info/metrics/$type/toMonth/$YYYY-DD
$type can be set to dataverses, datasets, files or downloads.
"""
url = "{0}/{1}".format(self.base_url_api_metrics, data_type)
if date_str:
url += "/toMonth/{0}".format(date_str)
return self.get_request(url, auth=auth)
def past_days(self, data_type, days_str, auth=DEPRECATION_GUARD):
"""
http://guides.dataverse.org/en/4.18.1/api/metrics.html
GET https://$SERVER/api/info/metrics/$type/pastDays/$days
$type can be set to dataverses, datasets, files or downloads.
"""
# TODO: check if date-string has proper format
url = "{0}/{1}/pastDays/{2}".format(
self.base_url_api_metrics, data_type, days_str
)
return self.get_request(url, auth=auth)
def get_dataverses_by_subject(self, auth=DEPRECATION_GUARD):
"""
GET https://$SERVER/api/info/metrics/dataverses/bySubject
$type can be set to dataverses, datasets, files or downloads.
"""
# TODO: check if date-string has proper format
url = "{0}/dataverses/bySubject".format(self.base_url_api_metrics)
return self.get_request(url, auth=auth)
def get_dataverses_by_category(self, auth=DEPRECATION_GUARD):
"""
GET https://$SERVER/api/info/metrics/dataverses/byCategory
$type can be set to dataverses, datasets, files or downloads.
"""
# TODO: check if date-string has proper format
url = "{0}/dataverses/byCategory".format(self.base_url_api_metrics)
return self.get_request(url, auth=auth)
def get_datasets_by_subject(self, date_str=None, auth=DEPRECATION_GUARD):
"""
GET https://$SERVER/api/info/metrics/datasets/bySubject
$type can be set to dataverses, datasets, files or downloads.
"""
# TODO: check if date-string has proper format
url = "{0}/datasets/bySubject".format(self.base_url_api_metrics)
if date_str:
url += "/toMonth/{0}".format(date_str)
return self.get_request(url, auth=auth)
def get_datasets_by_data_location(self, data_location, auth=DEPRECATION_GUARD):
"""
GET https://$SERVER/api/info/metrics/datasets/?dataLocation=$location
$type can be set to dataverses, datasets, files or downloads.
"""
# TODO: check if date-string has proper format
url = "{0}/datasets/?dataLocation={1}".format(
self.base_url_api_metrics, data_location
)
return self.get_request(url, auth=auth)
class NativeApi(Api):
"""Class to access Dataverse's Native API.
Parameters
----------
base_url : type
Description of parameter `base_url`.
api_token : type
Description of parameter `api_token`.
api_version : type
Description of parameter `api_version`.
Attributes
----------
base_url_api_native : type
Description of attribute `base_url_api_native`.
base_url_api : type
Description of attribute `base_url_api`.
"""
def __init__(self, base_url: str, api_token=None, api_version="v1", *, auth=None):
"""Init an Api() class.
Scheme, host and path combined create the base-url for the api.
See more about URL at `Wikipedia <https://en.wikipedia.org/wiki/URL>`_.
Parameters
----------
native_api_version : str
API version of Dataverse native API. Default is `v1`.
"""
super().__init__(base_url, api_token, api_version, auth=auth)
self.base_url_api_native = self.base_url_api
def get_dataverse(self, identifier, auth=DEPRECATION_GUARD):
"""Get dataverse metadata by alias or id.
View metadata about a dataverse.
.. code-block:: bash
GET http://$SERVER/api/dataverses/$id
Parameters
----------
identifier : str
Can either be a dataverse id (long), a dataverse alias (more
robust), or the special value ``:root``.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/dataverses/{1}".format(self.base_url_api_native, identifier)
return self.get_request(url, auth=auth)
def create_dataverse(
self, parent: str, metadata: str, auth: bool = True
) -> Response:
"""Create a dataverse.
Generates a new dataverse under identifier. Expects a JSON content
describing the dataverse.
HTTP Request:
.. code-block:: bash
POST http://$SERVER/api/dataverses/$id
Download the `dataverse.json <http://guides.dataverse.org/en/latest/
_downloads/dataverse-complete.json>`_ example file and modify to create
dataverses to suit your needs. The fields name, alias, and
dataverseContacts are required.
Status Codes:
200: dataverse created
201: dataverse created
Parameters
----------
parent : str
Parent dataverse, to which the Dataverse gets attached to.
metadata : str
Metadata of the Dataverse.
auth : bool
True if api authorization is necessary. Defaults to ``True``.
Returns
-------
httpx.Response
Response object of httpx library.
"""
metadata_dict = json.loads(metadata)
identifier = metadata_dict["alias"]
url = "{0}/dataverses/{1}".format(self.base_url_api_native, parent)
resp = self.post_request(url, metadata, auth)
if resp.status_code == 404:
error_msg = resp.json()["message"]
raise DataverseNotFoundError(
"ERROR: HTTP 404 - Dataverse {0} was not found. MSG: {1}".format(
parent, error_msg
)
)
elif resp.status_code != 200 and resp.status_code != 201:
error_msg = resp.json()["message"]
raise OperationFailedError(
"ERROR: HTTP {0} - Dataverse {1} could not be created. MSG: {2}".format(
resp.status_code, identifier, error_msg
)
)
else:
print("Dataverse {0} created.".format(identifier))
return resp
def publish_dataverse(self, identifier, auth=True):
"""Publish a dataverse.
Publish the Dataverse pointed by identifier, which can either by the
dataverse alias or its numerical id.
HTTP Request:
.. code-block:: bash
POST http://$SERVER/api/dataverses/$identifier/actions/:publish
Status Code:
200: Dataverse published
Parameters
----------
identifier : str
Can either be a dataverse id (long) or a dataverse alias (more
robust).
auth : bool
True if api authorization is necessary. Defaults to ``False``.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/dataverses/{1}/actions/:publish".format(
self.base_url_api_native, identifier
)
resp = self.post_request(url, auth=auth)
if resp.status_code == 401:
error_msg = resp.json()["message"]
raise ApiAuthorizationError(
"ERROR: HTTP 401 - Publish Dataverse {0} unauthorized. MSG: {1}".format(
identifier, error_msg
)
)
elif resp.status_code == 404:
error_msg = resp.json()["message"]
raise DataverseNotFoundError(
"ERROR: HTTP 404 - Dataverse {0} was not found. MSG: {1}".format(
identifier, error_msg
)
)
elif resp.status_code != 200:
error_msg = resp.json()["message"]
raise OperationFailedError(
"ERROR: HTTP {0} - Dataverse {1} could not be published. MSG: {2}".format(
resp.status_code, identifier, error_msg
)
)
elif resp.status_code == 200:
print("Dataverse {0} published.".format(identifier))
return resp
def delete_dataverse(self, identifier, auth=True):
"""Delete dataverse by alias or id.
Status Code:
200: Dataverse deleted
Parameters
----------
identifier : str
Can either be a dataverse id (long) or a dataverse alias (more
robust).
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/dataverses/{1}".format(self.base_url_api_native, identifier)
resp = self.delete_request(url, auth)
if resp.status_code == 401:
error_msg = resp.json()["message"]
raise ApiAuthorizationError(
"ERROR: HTTP 401 - Delete Dataverse {0} unauthorized. MSG: {1}".format(
identifier, error_msg
)
)
elif resp.status_code == 404:
error_msg = resp.json()["message"]
raise DataverseNotFoundError(
"ERROR: HTTP 404 - Dataverse {0} was not found. MSG: {1}".format(
identifier, error_msg
)
)
elif resp.status_code == 403:
error_msg = resp.json()["message"]
raise DataverseNotEmptyError(
"ERROR: HTTP 403 - Dataverse {0} not empty. MSG: {1}".format(
identifier, error_msg
)
)
elif resp.status_code != 200:
error_msg = resp.json()["message"]
raise OperationFailedError(
"ERROR: HTTP {0} - Dataverse {1} could not be deleted. MSG: {2}".format(
resp.status_code, identifier, error_msg
)
)
elif resp.status_code == 200:
print("Dataverse {0} deleted.".format(identifier))
return resp
def get_dataverse_roles(self, identifier: str, auth: bool = False) -> Response:
"""All the roles defined directly in the dataverse by identifier.
`Docs <https://guides.dataverse.org/en/latest/api/native-api.html#list-roles-defined-in-a-dataverse>`_
.. code-block:: bash
GET http://$SERVER/api/dataverses/$id/roles
Parameters
----------
identifier : str
Can either be a dataverse id (long), a dataverse alias (more
robust), or the special value ``:root``.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/dataverses/{1}/roles".format(self.base_url_api_native, identifier)
return self.get_request(url, auth=auth)
def get_dataverse_contents(self, identifier, auth=True):
"""Gets contents of Dataverse.
Parameters
----------
identifier : str
Can either be a dataverse id (long), a dataverse alias (more
robust), or the special value ``:root``.
auth : bool
Description of parameter `auth` (the default is False).
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/dataverses/{1}/contents".format(self.base_url_api_native, identifier)
return self.get_request(url, auth=auth)
def get_dataverse_assignments(self, identifier, auth=DEPRECATION_GUARD):
"""Get dataverse assignments by alias or id.
View assignments of a dataverse.
.. code-block:: bash
GET http://$SERVER/api/dataverses/$id/assignments
Parameters
----------
identifier : str
Can either be a dataverse id (long), a dataverse alias (more
robust), or the special value ``:root``.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/dataverses/{1}/assignments".format(
self.base_url_api_native, identifier
)
return self.get_request(url, auth=auth)
def get_dataverse_facets(self, identifier, auth=DEPRECATION_GUARD):
"""Get dataverse facets by alias or id.
View facets of a dataverse.
.. code-block:: bash
GET http://$SERVER/api/dataverses/$id/facets
Parameters
----------
identifier : str
Can either be a dataverse id (long), a dataverse alias (more
robust), or the special value ``:root``.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/dataverses/{1}/facets".format(self.base_url_api_native, identifier)
return self.get_request(url, auth=auth)
def dataverse_id2alias(self, dataverse_id, auth=DEPRECATION_GUARD):
"""Converts a Dataverse ID to an alias.
Parameters
----------
dataverse_id : str
Dataverse ID.
Returns
-------
str
Dataverse alias
"""
resp = self.get_dataverse(dataverse_id, auth=auth)
if "data" in resp.json():
if "alias" in resp.json()["data"]:
return resp.json()["data"]["alias"]
print("ERROR: Can not resolve Dataverse ID to alias.")
return False
def get_dataset(self, identifier, version=":latest", auth=True, is_pid=True):
"""Get metadata of a Dataset.
With Dataverse identifier:
.. code-block:: bash
GET http://$SERVER/api/datasets/$identifier
With persistent identifier:
.. code-block:: bash
GET http://$SERVER/api/datasets/:persistentId/?persistentId=$id
GET http://$SERVER/api/datasets/:persistentId/
?persistentId=$pid
Parameters
----------
identifier : str
Identifier of the dataset. Can be a Dataverse identifier or a
persistent identifier (e.g. ``doi:10.11587/8H3N93``).
is_pid : bool
True, if identifier is a persistent identifier.
version : str
Version to be retrieved:
``:latest-published``: the latest published version
``:latest``: either a draft (if exists) or the latest published version.
``:draft``: the draft version, if any
``x.y``: x.y a specific version, where x is the major version number and y is the minor version number.
``x``: same as x.0
Returns
-------
httpx.Response
Response object of httpx library.
"""
if is_pid:
# TODO: Add version to query http://guides.dataverse.org/en/4.18.1/api/native-api.html#get-json-representation-of-a-dataset
url = "{0}/datasets/:persistentId/?persistentId={1}".format(
self.base_url_api_native, identifier
)
else:
url = "{0}/datasets/{1}".format(self.base_url_api_native, identifier)
# CHECK: Its not really clear, if the version query can also be done via ID.
return self.get_request(url, auth=auth)
def get_dataset_versions(self, identifier, auth=True, is_pid=True):
"""Get versions of a Dataset.
With Dataverse identifier:
.. code-block:: bash
GET http://$SERVER/api/datasets/$identifier/versions
With persistent identifier:
.. code-block:: bash
GET http://$SERVER/api/datasets/:persistentId/versions?persistentId=$id
Parameters
----------
identifier : str
Identifier of the dataset. Can be a Dataverse identifier or a
persistent identifier (e.g. ``doi:10.11587/8H3N93``).
is_pid : bool
True, if identifier is a persistent identifier.
Returns
-------
httpx.Response
Response object of httpx library.
"""
if is_pid:
url = "{0}/datasets/:persistentId/versions?persistentId={1}".format(
self.base_url_api_native, identifier
)
else:
url = "{0}/datasets/{1}/versions".format(
self.base_url_api_native, identifier
)
return self.get_request(url, auth=auth)
def get_dataset_version(self, identifier, version, auth=True, is_pid=True):
"""Get version of a Dataset.
With Dataverse identifier:
.. code-block:: bash
GET http://$SERVER/api/datasets/$identifier/versions/$versionNumber
With persistent identifier:
.. code-block:: bash
GET http://$SERVER/api/datasets/:persistentId/versions/$versionNumber?persistentId=$id
Parameters
----------
identifier : str
Identifier of the dataset. Can be a Dataverse identifier or a
persistent identifier (e.g. ``doi:10.11587/8H3N93``).
version : str
Version string of the Dataset.
is_pid : bool
True, if identifier is a persistent identifier.
Returns
-------
httpx.Response
Response object of httpx library.
"""
if is_pid:
url = "{0}/datasets/:persistentId/versions/{1}?persistentId={2}".format(
self.base_url_api_native, version, identifier
)
else:
url = "{0}/datasets/{1}/versions/{2}".format(
self.base_url_api_native, identifier, version
)
return self.get_request(url, auth=auth)
def get_dataset_export(self, pid, export_format, auth=DEPRECATION_GUARD):
"""Get metadata of dataset exported in different formats.
Export the metadata of the current published version of a dataset
in various formats by its persistend identifier.
.. code-block:: bash
GET http://$SERVER/api/datasets/export?exporter=$exportformat&persistentId=$pid
Parameters
----------
pid : str
Persistent identifier of the dataset. (e.g. ``doi:10.11587/8H3N93``).
export_format : str
Export format as a string. Formats: ``ddi``, ``oai_ddi``,
``dcterms``, ``oai_dc``, ``schema.org``, ``dataverse_json``.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/datasets/export?exporter={1}&persistentId={2}".format(
self.base_url_api_native, export_format, pid
)
return self.get_request(url, auth=auth)
def create_dataset(self, dataverse, metadata, pid=None, publish=False, auth=True):
"""Add dataset to a dataverse.
`Dataverse Documentation
<http://guides.dataverse.org/en/latest/api/native-api.html#create-a-dataset-in-a-dataverse>`_
HTTP Request:
.. code-block:: bash
POST http://$SERVER/api/dataverses/$dataverse/datasets --upload-file FILENAME
Add new dataset with curl:
.. code-block:: bash
curl -H "X-Dataverse-key: $API_TOKEN" -X POST $SERVER_URL/api/dataverses/$DV_ALIAS/datasets --upload-file tests/data/dataset_min.json
Import dataset with existing persistend identifier with curl:
.. code-block:: bash
curl -H "X-Dataverse-key: $API_TOKEN" -X POST $SERVER_URL/api/dataverses/$DV_ALIAS/datasets/:import?pid=$PERSISTENT_IDENTIFIER&release=yes --upload-file tests/data/dataset_min.json
To create a dataset, you must create a JSON file containing all the
metadata you want such as example file: `dataset-finch1.json
<http://guides.dataverse.org/en/latest/_downloads/dataset-finch1.json>`_.
Then, you must decide which dataverse to create the dataset in and
target that datavese with either the "alias" of the dataverse (e.g.
"root") or the database id of the dataverse (e.g. "1"). The initial
version state will be set to "DRAFT":
Status Code:
201: dataset created
Import Dataset with existing PID:
`<http://guides.dataverse.org/en/latest/api/native-api.html#import-a-dataset-into-a-dataverse>`_
To import a dataset with an existing persistent identifier (PID), the
dataset’s metadata should be prepared in Dataverse’s native JSON format. The
PID is provided as a parameter at the URL. The following line imports a
dataset with the PID PERSISTENT_IDENTIFIER to Dataverse, and then releases it:
The pid parameter holds a persistent identifier (such as a DOI or Handle). The import will fail if no PID is provided, or if the provided PID fails validation.
The optional release parameter tells Dataverse to immediately publish the
dataset. If the parameter is changed to no, the imported dataset will
remain in DRAFT status.
Parameters
----------
dataverse : str
"alias" of the dataverse (e.g. ``root``) or the database id of the
dataverse (e.g. ``1``)
pid : str
PID of existing Dataset.
publish : bool
Publish only works when a Dataset with an existing PID is created. If it
is ``True``, Dataset should be instantly published, ``False``
if a Draft should be created.
metadata : str
Metadata of the Dataset as a json-formatted string (e. g.
`dataset-finch1.json <http://guides.dataverse.org/en/latest/_downloads/dataset-finch1.json>`_)
Returns
-------
httpx.Response
Response object of httpx library.
"""
if pid:
assert isinstance(pid, str)
url = "{0}/dataverses/{1}/datasets/:import?pid={2}".format(
self.base_url_api_native, dataverse, pid
)
if publish:
url += "&release=yes"
else:
url += "&release=no"
else:
url = "{0}/dataverses/{1}/datasets".format(
self.base_url_api_native, dataverse
)
resp = self.post_request(url, metadata, auth)
if resp.status_code == 404:
error_msg = resp.json()["message"]
raise DataverseNotFoundError(
"ERROR: HTTP 404 - Dataverse {0} was not found. MSG: {1}".format(
dataverse, error_msg
)
)
elif resp.status_code == 401:
error_msg = resp.json()["message"]
raise ApiAuthorizationError(
"ERROR: HTTP 401 - Create Dataset unauthorized. MSG: {0}".format(
error_msg
)
)
elif resp.status_code == 201:
if "data" in resp.json():
if "persistentId" in resp.json()["data"]:
identifier = resp.json()["data"]["persistentId"]
print("Dataset with pid '{0}' created.".format(identifier))
elif "id" in resp.json()["data"]:
identifier = resp.json()["data"]["id"]
print("Dataset with id '{0}' created.".format(identifier))
else:
print("ERROR: No identifier returned for created Dataset.")
return resp
def edit_dataset_metadata(
self, identifier, metadata, is_pid=True, replace=False, auth=True
):
"""Edit metadata of a given dataset.
`edit-dataset-metadata <http://guides.dataverse.org/en/latest/api/native-api.html#edit-dataset-metadata>`_.
HTTP Request:
.. code-block:: bash
PUT http://$SERVER/api/datasets/editMetadata/$id --upload-file FILENAME
Add data to dataset fields that are blank or accept multiple values with
the following
CURL Request:
.. code-block:: bash
curl -H "X-Dataverse-key: $API_TOKEN" -X PUT $SERVER_URL/api/datasets/:persistentId/editMetadata/?persistentId=$pid --upload-file dataset-add-metadata.json
For these edits your JSON file need only include those dataset fields
which you would like to edit. A sample JSON file may be downloaded
here: `dataset-edit-metadata-sample.json
<http://guides.dataverse.org/en/latest/_downloads/dataset-finch1.json>`_
Parameters
----------
identifier : str
Identifier of the dataset. Can be a Dataverse identifier or a
persistent identifier (e.g. ``doi:10.11587/8H3N93``).
metadata : str
Metadata of the Dataset as a json-formatted string.
is_pid : bool
``True`` to use persistent identifier. ``False``, if not.
replace : bool
``True`` to replace already existing metadata. ``False``, if not.
auth : bool
``True``, if an api token should be sent. Defaults to ``False``.
Returns
-------
httpx.Response
Response object of httpx library.
Examples
-------
Get dataset metadata::
>>> data = api.get_dataset(doi).json()["data"]["latestVersion"]["metadataBlocks"]["citation"]
>>> resp = api.edit_dataset_metadata(doi, data, is_replace=True, auth=True)
>>> resp.status_code
200: metadata updated
"""
if is_pid:
url = "{0}/datasets/:persistentId/editMetadata/?persistentId={1}".format(
self.base_url_api_native, identifier
)
else:
url = "{0}/datasets/editMetadata/{1}".format(
self.base_url_api_native, identifier
)
params = {"replace": True} if replace else {}
resp = self.put_request(url, metadata, auth, params)
if resp.status_code == 401:
error_msg = resp.json()["message"]
raise ApiAuthorizationError(
"ERROR: HTTP 401 - Updating metadata unauthorized. MSG: {0}".format(
error_msg
)
)
elif resp.status_code == 400:
if "Error parsing" in resp.json()["message"]:
print("Wrong passed data format.")
else:
print(
"You may not add data to a field that already has data and does not"
" allow multiples. Use is_replace=true to replace existing data."
)
elif resp.status_code == 200:
print("Dataset '{0}' updated".format(identifier))
return resp
def create_dataset_private_url(self, identifier, is_pid=True, auth=True):
"""Create private Dataset URL.
POST http://$SERVER/api/datasets/$id/privateUrl?key=$apiKey
http://guides.dataverse.org/en/4.16/api/native-api.html#create-a-private-url-for-a-dataset
'MSG: {1}'.format(pid, error_msg))
"""
if is_pid:
url = "{0}/datasets/:persistentId/privateUrl/?persistentId={1}".format(
self.base_url_api_native, identifier
)
else:
url = "{0}/datasets/{1}/privateUrl".format(
self.base_url_api_native, identifier
)
resp = self.post_request(url, auth=auth)
if resp.status_code == 200:
print(
"Dataset private URL created: {0}".format(resp.json()["data"]["link"])
)
return resp
def get_dataset_private_url(self, identifier, is_pid=True, auth=True):
"""Get private Dataset URL.
GET http://$SERVER/api/datasets/$id/privateUrl?key=$apiKey
http://guides.dataverse.org/en/4.16/api/native-api.html#get-the-private-url-for-a-dataset
"""
if is_pid:
url = "{0}/datasets/:persistentId/privateUrl/?persistentId={1}".format(
self.base_url_api_native, identifier
)
else:
url = "{0}/datasets/{1}/privateUrl".format(
self.base_url_api_native, identifier
)
resp = self.get_request(url, auth=auth)
if resp.status_code == 200:
print("Got Dataset private URL: {0}".format(resp.json()["data"]["link"]))
return resp
def delete_dataset_private_url(self, identifier, is_pid=True, auth=True):
"""Get private Dataset URL.
DELETE http://$SERVER/api/datasets/$id/privateUrl?key=$apiKey
http://guides.dataverse.org/en/4.16/api/native-api.html#delete-the-private-url-from-a-dataset
"""
if is_pid:
url = "{0}/datasets/:persistentId/privateUrl/?persistentId={1}".format(
self.base_url_api_native, identifier
)
else:
url = "{0}/datasets/{1}/privateUrl".format(
self.base_url_api_native, identifier
)
resp = self.delete_request(url, auth=auth)
if resp.status_code == 200:
print("Got Dataset private URL: {0}".format(resp.json()["data"]["link"]))
return resp
def publish_dataset(self, pid, release_type="minor", auth=True):
"""Publish dataset.
Publishes the dataset whose id is passed. If this is the first version
of the dataset, its version number will be set to 1.0. Otherwise, the
new dataset version number is determined by the most recent version
number and the type parameter. Passing type=minor increases the minor
version number (2.3 is updated to 2.4). Passing type=major increases
the major version number (2.3 is updated to 3.0). Superusers can pass
type=updatecurrent to update metadata without changing the version
number.
HTTP Request:
.. code-block:: bash
POST http://$SERVER/api/datasets/$id/actions/:publish?type=$type
When there are no default workflows, a successful publication process
will result in 200 OK response. When there are workflows, it is
impossible for Dataverse to know how long they are going to take and
whether they will succeed or not (recall that some stages might require
human intervention). Thus, a 202 ACCEPTED is returned immediately. To
know whether the publication process succeeded or not, the client code
has to check the status of the dataset periodically, or perform some
push request in the post-publish workflow.
Status Code:
200: dataset published
Parameters
----------
pid : str
Persistent identifier of the dataset (e.g.
``doi:10.11587/8H3N93``).
release_type : str
Passing ``minor`` increases the minor version number (2.3 is
updated to 2.4). Passing ``major`` increases the major version
number (2.3 is updated to 3.0). Superusers can pass
``updatecurrent`` to update metadata without changing the version
number.
auth : bool
``True`` if api authorization is necessary. Defaults to ``False``.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/datasets/:persistentId/actions/:publish".format(
self.base_url_api_native
)
url += "?persistentId={0}&type={1}".format(pid, release_type)
resp = self.post_request(url, auth=auth)
if resp.status_code == 404:
error_msg = resp.json()["message"]
raise DatasetNotFoundError(
"ERROR: HTTP 404 - Dataset {0} was not found. MSG: {1}".format(
pid, error_msg
)
)
elif resp.status_code == 401:
error_msg = resp.json()["message"]
raise ApiAuthorizationError(
"ERROR: HTTP 401 - User not allowed to publish dataset {0}. "
"MSG: {1}".format(pid, error_msg)
)
elif resp.status_code == 200:
print("Dataset {0} published".format(pid))
return resp
def get_dataset_lock(self, pid):
"""Get if dataset is locked.
The lock API endpoint was introduced in Dataverse 4.9.3.
Parameters
----------
pid : str
Persistent identifier of the Dataset (e.g.
``doi:10.11587/8H3N93``).
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/datasets/:persistentId/locks/?persistentId={1}".format(
self.base_url_api_native, pid
)
return self.get_request(url, auth=True)
def get_dataset_assignments(self, identifier, is_pid=True, auth=True):
"""Get Dataset assignments.
GET http://$SERVER/api/datasets/$id/assignments?key=$apiKey
"""
if is_pid:
url = "{0}/datasets/:persistentId/assignments/?persistentId={1}".format(
self.base_url_api_native, identifier
)
else:
url = "{0}/datasets/{1}/assignments".format(
self.base_url_api_native, identifier
)
return self.get_request(url, auth=auth)
def delete_dataset(self, identifier, is_pid=True, auth=True):
"""Delete a dataset.
Delete the dataset whose id is passed
Status Code:
200: dataset deleted
Parameters
----------
identifier : str
Identifier of the dataset. Can be a Dataverse identifier or a
persistent identifier (e.g. ``doi:10.11587/8H3N93``).
is_pid : bool
True, if identifier is a persistent identifier.
Returns
-------
httpx.Response
Response object of httpx library.
"""
if is_pid:
url = "{0}/datasets/:persistentId/?persistentId={1}".format(
self.base_url_api_native, identifier
)
else:
url = "{0}/datasets/{1}".format(self.base_url_api_native, identifier)
resp = self.delete_request(url, auth=auth)
if resp.status_code == 404:
error_msg = resp.json()["message"]
raise DatasetNotFoundError(
"ERROR: HTTP 404 - Dataset '{0}' was not found. MSG: {1}".format(
identifier, error_msg
)
)
elif resp.status_code == 405:
error_msg = resp.json()["message"]
raise OperationFailedError(
"ERROR: HTTP 405 - "
"Published datasets can only be deleted from the GUI. For "
"more information, please refer to "
"https://github.com/IQSS/dataverse/issues/778"
" MSG: {0}".format(error_msg)
)
elif resp.status_code == 401:
error_msg = resp.json()["message"]
raise ApiAuthorizationError(
"ERROR: HTTP 401 - User not allowed to delete dataset '{0}'. "
"MSG: {1}".format(identifier, error_msg)
)
elif resp.status_code == 200:
print("Dataset '{0}' deleted.".format(identifier))
return resp
def destroy_dataset(self, identifier, is_pid=True, auth=True):
"""Destroy Dataset.
http://guides.dataverse.org/en/4.16/api/native-api.html#delete-published-dataset
Normally published datasets should not be deleted, but there exists a
“destroy” API endpoint for superusers which will act on a dataset given
a persistent ID or dataset database ID:
curl -H "X-Dataverse-key:$API_TOKEN" -X DELETE http://$SERVER/api/datasets/:persistentId/destroy/?persistentId=doi:10.5072/FK2/AAA000
curl -H "X-Dataverse-key:$API_TOKEN" -X DELETE http://$SERVER/api/datasets/999/destroy
Calling the destroy endpoint is permanent and irreversible. It will
remove the dataset and its datafiles, then re-index the parent
dataverse in Solr. This endpoint requires the API token of a
superuser.
"""
if is_pid:
url = "{0}/datasets/:persistentId/destroy/?persistentId={1}".format(
self.base_url_api_native, identifier
)
else:
url = "{0}/datasets/{1}/destroy".format(
self.base_url_api_native, identifier
)
resp = self.delete_request(url, auth=auth)
if resp.status_code == 200:
print("Dataset {0} destroyed".format(resp.json()))
return resp
def get_datafiles_metadata(self, pid, version=":latest", auth=True):
"""List metadata of all datafiles of a dataset.
`Documentation <http://guides.dataverse.org/en/latest/api/native-api.html#list-files-in-a-dataset>`_
HTTP Request:
.. code-block:: bash
GET http://$SERVER/api/datasets/$id/versions/$versionId/files
Parameters
----------
pid : str
Persistent identifier of the dataset. e.g. ``doi:10.11587/8H3N93``.
version : str
Version of dataset. Defaults to `1`.
Returns
-------
httpx.Response
Response object of httpx library.
"""
base_str = "{0}/datasets/:persistentId/versions/".format(
self.base_url_api_native
)
url = base_str + "{0}/files?persistentId={1}".format(version, pid)
return self.get_request(url, auth=auth)
def get_datafile_metadata(
self, identifier, is_filepid=False, is_draft=False, auth=True
):
"""
GET http://$SERVER/api/files/{id}/metadata
curl $SERVER_URL/api/files/$ID/metadata
curl "$SERVER_URL/api/files/:persistentId/metadata?persistentId=$PERSISTENT_ID"
curl "https://demo.dataverse.org/api/files/:persistentId/metadata?persistentId=doi:10.5072/FK2/AAA000"
curl -H "X-Dataverse-key:$API_TOKEN" $SERVER_URL/api/files/$ID/metadata/draft
"""
if is_filepid:
url = "{0}/files/:persistentId/metadata".format(self.base_url_api_native)
if is_draft:
url += "/draft"
url += "?persistentId={0}".format(identifier)
else:
url = "{0}/files/{1}/metadata".format(self.base_url_api_native, identifier)
if is_draft:
url += "/draft"
# CHECK: Its not really clear, if the version query can also be done via ID.
return self.get_request(url, auth=auth)
def upload_datafile(self, identifier, filename, json_str=None, is_pid=True):
"""Add file to a dataset.
Add a file to an existing Dataset. Description and tags are optional:
HTTP Request:
.. code-block:: bash
POST http://$SERVER/api/datasets/$id/add
The upload endpoint checks the content of the file, compares it with
existing files and tells if already in the database (most likely via
hashing).
`adding-files <http://guides.dataverse.org/en/latest/api/native-api.html#adding-files>`_.
Parameters
----------
identifier : str
Identifier of the dataset.
filename : str
Full filename with path.
json_str : str
Metadata as JSON string.
is_pid : bool
``True`` to use persistent identifier. ``False``, if not.
Returns
-------
dict
The json string responded by the CURL request, converted to a
dict().
"""
url = self.base_url_api_native
if is_pid:
url += "/datasets/:persistentId/add?persistentId={0}".format(identifier)
else:
url += "/datasets/{0}/add".format(identifier)
files = {"file": open(filename, "rb")}
metadata = {}
if json_str is not None:
metadata["jsonData"] = json_str
return self.post_request(url, data=metadata, files=files, auth=True)
def update_datafile_metadata(self, identifier, json_str=None, is_filepid=False):
"""Update datafile metadata.
metadata such as description, directoryLabel (File Path) and tags are not carried over from the file being replaced:
Updates the file metadata for an existing file where ID is the
database id of the file to update or PERSISTENT_ID is the persistent id
(DOI or Handle) of the file. Requires a jsonString expressing the new
metadata. No metadata from the previous version of this file will be
persisted, so if you want to update a specific field first get the
json with the above command and alter the fields you want.
Also note that dataFileTags are not versioned and changes to these will update the published version of the file.
This functions needs CURL to work!
HTTP Request:
.. code-block:: bash
POST -F 'file=@file.extension' -F 'jsonData={json}' http://$SERVER/api/files/{id}/metadata?key={apiKey}
curl -H "X-Dataverse-key:$API_TOKEN" -X POST -F 'jsonData={"description":"My description bbb.","provFreeform":"Test prov freeform","categories":["Data"],"restrict":false}' $SERVER_URL/api/files/$ID/metadata
curl -H "X-Dataverse-key:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" -X POST -F 'jsonData={"description":"My description bbb.","provFreeform":"Test prov freeform","categories":["Data"],"restrict":false}' "https://demo.dataverse.org/api/files/:persistentId/metadata?persistentId=doi:10.5072/FK2/AAA000"
`Docs <http://guides.dataverse.org/en/latest/api/native-api.html#updating-file-metadata>`_.
Parameters
----------
identifier : str
Identifier of the dataset.
json_str : str
Metadata as JSON string.
is_filepid : bool
``True`` to use persistent identifier for datafile. ``False``, if
not.
Returns
-------
dict
The json string responded by the CURL request, converted to a
dict().
"""
# if is_filepid:
# url = '{0}/files/:persistentId/metadata?persistentId={1}'.format(
# self.base_url_api_native, identifier)
# else:
# url = '{0}/files/{1}/metadata'.format(self.base_url_api_native, identifier)
#
# data = {'jsonData': json_str}
# resp = self.post_request(
# url,
# data=data,
# auth=True
# )
query_str = self.base_url_api_native
if is_filepid:
query_str = "{0}/files/:persistentId/metadata?persistentId={1}".format(
self.base_url_api_native, identifier
)
else:
query_str = "{0}/files/{1}/metadata".format(
self.base_url_api_native, identifier
)
shell_command = 'curl -H "X-Dataverse-key: {0}"'.format(self.api_token)
shell_command += " -X POST -F 'jsonData={0}' {1}".format(json_str, query_str)
# TODO(Shell): is shell=True necessary?
return sp.run(shell_command, shell=True, stdout=sp.PIPE)
def replace_datafile(self, identifier, filename, json_str, is_filepid=True):
"""Replace datafile.
HTTP Request:
.. code-block:: bash
POST -F 'file=@file.extension' -F 'jsonData={json}' http://$SERVER/api/files/{id}/replace?key={apiKey}
`replacing-files <http://guides.dataverse.org/en/latest/api/native-api.html#replacing-files>`_.
Parameters
----------
identifier : str
Identifier of the file to be replaced.
filename : str
Full filename with path.
json_str : str
Metadata as JSON string.
is_filepid : bool
``True`` if ``identifier`` is a persistent identifier for the datafile.
``False``, if not.
Returns
-------
dict
The json string responded by the CURL request, converted to a
dict().
"""
url = self.base_url_api_native
files = {"file": open(filename, "rb")}
data = {"jsonData": json_str}
if is_filepid:
url += "/files/:persistentId/replace?persistentId={0}".format(identifier)
else:
url += "/files/{0}/replace".format(identifier)
return self.post_request(url, data=data, files=files, auth=True)
def get_info_version(self, auth=DEPRECATION_GUARD):
"""Get the Dataverse version and build number.
The response contains the version and build numbers. Requires no api
token.
HTTP Request:
.. code-block:: bash
GET http://$SERVER/api/info/version
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/info/version".format(self.base_url_api_native)
return self.get_request(url, auth=auth)
def get_info_server(self, auth=DEPRECATION_GUARD):
"""Get dataverse server name.
This is useful when a Dataverse system is composed of multiple Java EE
servers behind a load balancer.
HTTP Request:
.. code-block:: bash
GET http://$SERVER/api/info/server
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/info/server".format(self.base_url_api_native)
return self.get_request(url, auth=auth)
def get_info_api_terms_of_use(self, auth=DEPRECATION_GUARD):
"""Get API Terms of Use url.
The response contains the text value inserted as API Terms of use which
uses the database setting :ApiTermsOfUse.
HTTP Request:
.. code-block:: bash
GET http://$SERVER/api/info/apiTermsOfUse
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/info/apiTermsOfUse".format(self.base_url_api_native)
return self.get_request(url, auth=auth)
def get_metadatablocks(self, auth=DEPRECATION_GUARD):
"""Get info about all metadata blocks.
Lists brief info about all metadata blocks registered in the system.
HTTP Request:
.. code-block:: bash
GET http://$SERVER/api/metadatablocks
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/metadatablocks".format(self.base_url_api_native)
return self.get_request(url, auth=auth)
def get_metadatablock(self, identifier, auth=DEPRECATION_GUARD):
"""Get info about single metadata block.
Returns data about the block whose identifier is passed. identifier can
either be the block’s id, or its name.
HTTP Request:
.. code-block:: bash
GET http://$SERVER/api/metadatablocks/$identifier
Parameters
----------
identifier : str
Can be block's id, or it's name.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/metadatablocks/{1}".format(self.base_url_api_native, identifier)
return self.get_request(url, auth=auth)
def get_user_api_token_expiration_date(self, auth=DEPRECATION_GUARD):
"""Get the expiration date of an Users's API token.
HTTP Request:
.. code-block:: bash
curl -H X-Dataverse-key:$API_TOKEN -X GET $SERVER_URL/api/users/token
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/users/token".format(self.base_url_api_native)
return self.get_request(url, auth=auth)
def recreate_user_api_token(self):
"""Recreate an Users API token.
HTTP Request:
.. code-block:: bash
curl -H X-Dataverse-key:$API_TOKEN -X POST $SERVER_URL/api/users/token/recreate
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/users/token/recreate".format(self.base_url_api_native)
return self.post_request(url)
def delete_user_api_token(self):
"""Delete an Users API token.
HTTP Request:
.. code-block:: bash
curl -H X-Dataverse-key:$API_TOKEN -X POST $SERVER_URL/api/users/token/recreate
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/users/token".format(self.base_url_api_native)
return self.delete_request(url)
def create_role(self, dataverse_id):
"""Create a new role.
`Docs <https://guides.dataverse.org/en/latest/api/native-api.html#id2>`_
HTTP Request:
.. code-block:: bash
POST http://$SERVER/api/roles?dvo=$dataverseIdtf&key=$apiKey
Parameters
----------
dataverse_id : str
Can be alias or id of a Dataverse.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/roles?dvo={1}".format(self.base_url_api_native, dataverse_id)
return self.post_request(url)
def show_role(self, role_id, auth=DEPRECATION_GUARD):
"""Show role.
`Docs <https://guides.dataverse.org/en/latest/api/native-api.html#show-role>`_
HTTP Request:
.. code-block:: bash
GET http://$SERVER/api/roles/$id
Parameters
----------
identifier : str
Can be alias or id of a Dataverse.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/roles/{1}".format(self.base_url_api_native, role_id)
return self.get_request(url, auth=auth)
def delete_role(self, role_id):
"""Delete role.
`Docs <https://guides.dataverse.org/en/latest/api/native-api.html#delete-role>`_
Parameters
----------
identifier : str
Can be alias or id of a Dataverse.
Returns
-------
httpx.Response
Response object of httpx library.
"""
url = "{0}/roles/{1}".format(self.base_url_api_native, role_id)
return self.delete_request(url)
def get_children(
self, parent=":root", parent_type="dataverse", children_types=None, auth=True
):
"""Walk through children of parent element in Dataverse tree.
Default: gets all child dataverses if parent = dataverse or all
Example Dataverse Tree:
.. code-block:: bash
data = {
'type': 'dataverse',
'dataverse_id': 1,
'dataverse_alias': ':root',
'children': [
{
'type': 'datasets',
'dataset_id': 231,
'pid': 'doi:10.11587/LYFDYC',
'children': [
{
'type': 'datafile'
'datafile_id': 532,
'pid': 'doi:10.11587/LYFDYC/C2WTRN',
'filename': '10082_curation.pdf '
}
]
}
]
}
Parameters
----------
parent : str
Description of parameter `parent`.
parent_type : str
Description of parameter `parent_type`.
children_types : list
Types of children to be collected. 'dataverses', 'datasets' and 'datafiles' are valid list items.
auth : bool
Authentication needed
Returns
-------
list
List of Dataverse data type dictionaries. Different ones for
Dataverses, Datasets and Datafiles.
# TODO
- differentiate between published and unpublished data types
- util function to read out all dataverses into a list
- util function to read out all datasets into a list
- util function to read out all datafiles into a list
- Unify tree and models
"""
children = []
if children_types is None:
children_types = []
if len(children_types) == 0:
if parent_type == "dataverse":
children_types = ["dataverses"]
elif parent_type == "dataset":
children_types = ["datafiles"]
if (
"dataverses" in children_types
and "datafiles" in children_types
and "datasets" not in children_types
):
print(
"ERROR: Wrong children_types passed: 'dataverses' and 'datafiles'"
" passed, 'datasets' missing."
)
return False
if parent_type == "dataverse":
# check for dataverses and datasets as children and get their ID
parent_alias = parent
resp = self.get_dataverse_contents(parent_alias, auth=auth)
if "data" in resp.json():
contents = resp.json()["data"]
for content in contents:
if (
content["type"] == "dataverse"
and "dataverses" in children_types
):
dataverse_id = content["id"]
child_alias = self.dataverse_id2alias(dataverse_id, auth=auth)
children.append(
{
"dataverse_id": dataverse_id,
"title": content["title"],
"dataverse_alias": child_alias,
"type": "dataverse",
"children": self.get_children(
parent=child_alias,
parent_type="dataverse",
children_types=children_types,
auth=auth,
),
}
)
elif content["type"] == "dataset" and "datasets" in children_types:
pid = (
content["protocol"]
+ ":"
+ content["authority"]
+ "/"
+ content["identifier"]
)
children.append(
{
"dataset_id": content["id"],
"pid": pid,
"type": "dataset",
"children": self.get_children(
parent=pid,
parent_type="dataset",
children_types=children_types,
auth=auth,
),
}
)
else:
print("ERROR: 'get_dataverse_contents()' API request not working.")
elif parent_type == "dataset" and "datafiles" in children_types:
# check for datafiles as children and get their ID
pid = parent
resp = self.get_datafiles_metadata(parent, version=":latest")
if "data" in resp.json():
for datafile in resp.json()["data"]:
children.append(
{
"datafile_id": datafile["dataFile"]["id"],
"filename": datafile["dataFile"]["filename"],
"label": datafile["label"],
"pid": datafile["dataFile"]["persistentId"],
"type": "datafile",
}
)
else:
print("ERROR: 'get_datafiles()' API request not working.")
return children
def get_user(self):
"""Get details of the current authenticated user.
Auth must be ``true`` for this to work. API endpoint is available for Dataverse >= 5.3.
https://guides.dataverse.org/en/latest/api/native-api.html#get-user-information-in-json-format
"""
url = f"{self.base_url}/users/:me"
return self.get_request(url, auth=True)
def redetect_file_type(
self, identifier: str, is_pid: bool = False, dry_run: bool = False
) -> Response:
"""Redetect file type.
https://guides.dataverse.org/en/latest/api/native-api.html#redetect-file-type
Parameters
----------
identifier : str
Datafile id (fileid) or file PID.
is_pid : bool
Is the identifier a PID, by default False.
dry_run : bool, optional
[description], by default False
Returns
-------
Response
Request Response() object.
"""
if dry_run is True:
dry_run_str = "true"
elif dry_run is False:
dry_run_str = "false"
if is_pid:
url = f"{self.base_url_api_native}/files/:persistentId/redetect?persistentId={identifier}&dryRun={dry_run_str}"
else:
url = f"{self.base_url_api_native}/files/{identifier}/redetect?dryRun={dry_run_str}"
return self.post_request(url, auth=True)
def reingest_datafile(self, identifier: str, is_pid: bool = False) -> Response:
"""Reingest datafile.
https://guides.dataverse.org/en/latest/api/native-api.html#reingest-a-file
Parameters
----------
identifier : str
Datafile id (fileid) or file PID.
is_pid : bool
Is the identifier a PID, by default False.
Returns
-------
Response
Request Response() object.
"""
if is_pid:
url = f"{self.base_url_api_native}/files/:persistentId/reingest?persistentId={identifier}"
else:
url = f"{self.base_url_api_native}/files/{identifier}/reingest"
return self.post_request(url, auth=True)
def uningest_datafile(self, identifier: str, is_pid: bool = False) -> Response:
"""Uningest datafile.
https://guides.dataverse.org/en/latest/api/native-api.html#uningest-a-file
Parameters
----------
identifier : str
Datafile id (fileid) or file PID.
is_pid : bool
Is the identifier a PID, by default False.
Returns
-------
Response
Request Response() object.
"""
if is_pid:
url = f"{self.base_url_api_native}/files/:persistentId/uningest?persistentId={identifier}"
else:
url = f"{self.base_url_api_native}/files/{identifier}/uningest"
return self.post_request(url, auth=True)
def restrict_datafile(self, identifier: str, is_pid: bool = False) -> Response:
"""Uningest datafile.
https://guides.dataverse.org/en/latest/api/native-api.html#restrict-files
Parameters
----------
identifier : str
Datafile id (fileid) or file PID.
is_pid : bool
Is the identifier a PID, by default False.
Returns
-------
Response
Request Response() object.
"""
if is_pid:
url = f"{self.base_url_api_native}/files/:persistentId/restrict?persistentId={identifier}"
else:
url = f"{self.base_url_api_native}/files/{identifier}/restrict"
return self.put_request(url, auth=True)
class SearchApi(Api):
"""Class to access Dataverse's Search API.
Examples
-------
Examples should be written in doctest format, and
should illustrate how to use the function/class.
>>>
Attributes
----------
base_url_api_search : type
Description of attribute `base_url_api_search`.
base_url : type
Description of attribute `base_url`.
"""
def __init__(self, base_url, api_token=None, api_version="latest", *, auth=None):
"""Init an SearchApi() class."""
super().__init__(base_url, api_token, api_version, auth=auth)
if base_url:
self.base_url_api_search = "{0}/search?q=".format(self.base_url_api)
else:
self.base_url_api_search = self.base_url_api
def search(
self,
q_str,
data_type=None,
subtree=None,
sort=None,
order=None,
per_page=None,
start=None,
show_relevance=None,
show_facets=None,
filter_query=None,
show_entity_ids=None,
query_entities=None,
auth=DEPRECATION_GUARD,
):
"""Search.
http://guides.dataverse.org/en/4.18.1/api/search.html
"""
url = "{0}{1}".format(self.base_url_api_search, q_str)
if data_type:
# TODO: pass list of types
url += "&type={0}".format(data_type)
if subtree:
# TODO: pass list of subtrees
url += "&subtree={0}".format(subtree)
if sort:
url += "&sort={0}".format(sort)
if order:
url += "&order={0}".format(order)
if per_page:
url += "&per_page={0}".format(per_page)
if start:
url += "&start={0}".format(start)
if show_relevance:
url += "&show_relevance={0}".format(show_relevance)
if show_facets:
url += "&show_facets={0}".format(show_facets)
if filter_query:
url += "&fq={0}".format(filter_query)
if show_entity_ids:
url += "&show_entity_ids={0}".format(show_entity_ids)
if query_entities:
url += "&query_entities={0}".format(query_entities)
return self.get_request(url, auth=auth)
class SwordApi(Api):
"""Class to access Dataverse's SWORD API.
Parameters
----------
sword_api_version : str
SWORD API version. Defaults to 'v1.1'.
Attributes
----------
base_url_api_sword : str
Description of attribute `base_url_api_sword`.
base_url : str
Description of attribute `base_url`.
native_api_version : str
Description of attribute `native_api_version`.
sword_api_version
"""
def __init__(
self,
base_url,
api_version="v1.1",
api_token=None,
sword_api_version="v1.1",
*,
auth=None,
):
"""Init a :class:`SwordApi <pyDataverse.api.SwordApi>` instance.
Parameters
----------
sword_api_version : str
Api version of Dataverse SWORD API.
api_token : str | None
An Api token as retrieved from your Dataverse instance.
auth : httpx.Auth
Note that the SWORD API uses a different authentication mechanism
than the native API, in particular it uses `HTTP Basic
Authentication
<https://guides.dataverse.org/en/latest/api/sword.html#sword-auth>`_.
Thus, if you pass an api_token, it will be used as the username in
the HTTP Basic Authentication. If you pass a custom :py:class:`httpx.Auth`, use
:py:class:`httpx.BasicAuth` with an empty password:
.. code-block:: python
sword_api = Api(
"https://demo.dataverse.org", auth=httpx.BasicAuth(username="my_token", password="")
)
"""
if auth is None and api_token is not None:
auth = httpx.BasicAuth(api_token, "")
super().__init__(base_url, api_token, api_version, auth=auth)
if not isinstance(sword_api_version, ("".__class__, "".__class__)):
raise ApiUrlError(
"sword_api_version {0} is not a string.".format(sword_api_version)
)
self.sword_api_version = sword_api_version
# Test connection.
if self.base_url and sword_api_version:
self.base_url_api_sword = "{0}/dvn/api/data-deposit/{1}".format(
self.base_url, self.sword_api_version
)
else:
self.base_url_api_sword = base_url
def get_service_document(self):
url = "{0}/swordv2/service-document".format(self.base_url_api_sword)
return self.get_request(url, auth=True)
|