forked from gdcc/pyDataverse
-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.py
1150 lines (930 loc) · 37.4 KB
/
api.py
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
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Dataverse API connector."""
from datetime import datetime
import json
from pyDataverse.exceptions import ApiAuthorizationError
from pyDataverse.exceptions import ApiResponseError
from pyDataverse.exceptions import ApiUrlError
from pyDataverse.exceptions import DatasetNotFoundError
from pyDataverse.exceptions import DataverseNotEmptyError
from pyDataverse.exceptions import DataverseNotFoundError
from pyDataverse.exceptions import OperationFailedError
from requests import ConnectionError
from requests import delete
from requests import get
from requests import post
from requests import put
import subprocess as sp
class Api(object):
"""API class.
Parameters
----------
base_url : string
Base URL of Dataverse instance. Without trailing `/` at the end.
e.g. `http://demo.dataverse.org`
api_token : string
Authenication token for the api.
api_version : string
Dataverse api version. Defaults to `v1`.
Attributes
----------
conn_started : datetime
Time when `Api()` was instantiated, the connection got established.
native_api_base_url : string
Url of Dataverse's native Api.
base_url
api_token
api_version
"""
def __init__(self, base_url, api_token=None, api_version='v1'):
"""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 : string
Base url for Dataverse api.
api_token : string
Api token for Dataverse api.
api_version : string
Api version of Dataverse native api. Default is `v1`.
Examples
-------
Create an Api connection::
>>> from pyDataverse.api import Api
>>> base_url = 'http://demo.dataverse.org'
>>> api = Api(base_url)
>>> api.status
'OK'
"""
# Check and set basic variables.
if not isinstance(base_url, ("".__class__, u"".__class__)):
raise ApiUrlError('base_url {0} is not a string.'.format(base_url))
self.base_url = base_url
if not isinstance(api_version, ("".__class__, u"".__class__)):
raise ApiUrlError('api_version {0} is not a string.'.format(
api_version))
self.api_version = api_version
if api_token:
if not isinstance(api_token, ("".__class__, u"".__class__)):
raise ApiAuthorizationError(
'Api token passed is not a string.')
self.api_token = api_token
self.conn_started = datetime.now()
# Test connection.
query_str = '/info/server'
if base_url and api_version:
self.native_api_base_url = '{0}/api/{1}'.format(self.base_url,
self.api_version)
url = '{0}{1}'.format(self.native_api_base_url, query_str)
try:
resp = get(url)
if resp:
self.status = resp.json()['status']
else:
self.status = 'ERROR'
raise ApiResponseError(
'No response from api request {0}.'.format(url)
)
except KeyError as e:
print('ERROR: Key not in response {0} {1}.'.format(e, url))
except ConnectionError as e:
self.status = 'ERROR'
print(
'ERROR: Could not establish connection to url {0} {1}.'
''.format(url, e))
else:
self.status = 'ERROR'
self.native_api_base_url = None
def __str__(self):
"""Return name of Api() class for users.
Returns
-------
string
Naming of the Api() class.
"""
return 'pyDataverse API class'
def get_request(self, query_str, params=None, auth=False):
"""Make a GET request.
Parameters
----------
query_str : string
Query string for the request. Will be concatenated to
`native_api_base_url`.
params : dict
Dictionary of parameters to be passed with the request.
Defaults to `None`.
auth : bool
Should an api token be sent in the request. Defaults to `False`.
Returns
-------
requests.Response
Response object of requests library.
"""
url = '{0}{1}'.format(self.native_api_base_url, query_str)
if auth:
if self.api_token:
if not params:
params = {}
params['key'] = self.api_token
else:
ApiAuthorizationError(
'ERROR: GET - Api token not passed to '
'`get_request` {}.'.format(url)
)
try:
resp = get(
url,
params=params
)
if resp:
if resp.status_code == 401:
error_msg = resp.json()['message']
raise ApiAuthorizationError(
'ERROR: GET - Authorization invalid {0}. MSG: {1}.'
''.format(url, error_msg)
)
elif resp.status_code >= 300:
error_msg = resp.json()['message']
raise OperationFailedError(
'ERROR: GET HTTP {0} - {1}. MSG: {2}'.format(
resp.status_code, url, error_msg)
)
return resp
except ConnectionError:
raise ConnectionError(
'ERROR: GET - Could not establish connection to api {}.'
''.format(url)
)
def post_request(self, query_str, metadata=None, auth=False,
params=None):
"""Make a POST request.
Parameters
----------
query_str : string
Query string for the request. Will be concatenated to
`native_api_base_url`.
metadata : string
Metadata as a json-formatted string. Defaults to `None`.
auth : bool
Should an api token be sent in the request. Defaults to `False`.
params : dict
Dictionary of parameters to be passed with the request.
Defaults to `None`.
Returns
-------
requests.Response
Response object of requests library.
"""
url = '{0}{1}'.format(self.native_api_base_url, query_str)
if auth:
if self.api_token:
if not params:
params = {}
params['key'] = self.api_token
else:
ApiAuthorizationError(
'ERROR: POST - Api token not passed to '
'`post_request` {}.'.format(url)
)
try:
resp = post(
url,
data=metadata,
params=params
)
if resp.status_code == 401:
error_msg = resp.json()['message']
raise ApiAuthorizationError(
'ERROR: POST HTTP 401 - Authorization error {0}. MSG: {1}'
''.format(url, error_msg)
)
return resp
except ConnectionError:
raise ConnectionError(
'ERROR: POST - Could not establish connection to api {}.'
''.format(url)
)
def put_request(self, query_str, metadata=None, auth=False,
params=None):
"""Make a PUT request.
Parameters
----------
query_str : string
Query string for the request. Will be concatenated to
`native_api_base_url`.
metadata : string
Metadata as a json-formatted string. Defaults to `None`.
auth : bool
Should an api token be sent in the request. Defaults to `False`.
params : dict
Dictionary of parameters to be passed with the request.
Defaults to `None`.
Returns
-------
requests.Response
Response object of requests library.
"""
url = '{0}{1}'.format(self.native_api_base_url, query_str)
if auth:
if self.api_token:
if not params:
params = {}
params['key'] = self.api_token
else:
ApiAuthorizationError(
'ERROR: PUT - Api token not passed to '
'`put_request` {}.'.format(url)
)
try:
resp = put(
url,
data=metadata,
params=params
)
if resp.status_code == 401:
error_msg = resp.json()['message']
raise ApiAuthorizationError(
'ERROR: PUT HTTP 401 - Authorization error {0}. MSG: {1}'
''.format(url, error_msg)
)
return resp
except ConnectionError:
raise ConnectionError(
'ERROR: PUT - Could not establish connection to api {}.'
''.format(url)
)
def delete_request(self, query_str, auth=False, params=None):
"""Make a DELETE request.
Parameters
----------
query_str : string
Query string for the request. Will be concatenated to
`native_api_base_url`.
auth : bool
Should an api token be sent in the request. Defaults to `False`.
params : dict
Dictionary of parameters to be passed with the request.
Defaults to `None`.
Returns
-------
requests.Response
Response object of requests library.
"""
url = '{0}{1}'.format(self.native_api_base_url, query_str)
if auth:
if self.api_token:
if not params:
params = {}
params['key'] = self.api_token
else:
ApiAuthorizationError(
'ERROR: DELETE - Api token not passed to '
'`delete_request` {}.'.format(url)
)
try:
resp = delete(
url,
params=params
)
return resp
except ConnectionError:
raise ConnectionError(
'ERROR: DELETE could not establish connection to api {}.'
''.format(url)
)
def get_dataverse(self, identifier, auth=False):
"""Get dataverse metadata by alias or id.
View metadata about a dataverse.
.. code-block:: bash
GET http://$SERVER/api/dataverses/$id
Parameters
----------
identifier : string
Can either be a dataverse id (long), a dataverse alias (more
robust), or the special value ``:root``.
Returns
-------
requests.Response
Response object of requests library.
"""
query_str = '/dataverses/{0}'.format(identifier)
resp = self.get_request(query_str, auth=auth)
return resp
def create_dataverse(self, identifier, metadata, auth=True,
parent=':root'):
"""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
----------
identifier : string
Can either be a dataverse id (long) or a dataverse alias (more
robust). If identifier is omitted, a root dataverse is created.
metadata : string
Metadata of the Dataverse as a json-formatted string.
auth : bool
True if api authorization is necessary. Defaults to ``True``.
parent : string
Parent dataverse, if existing, to which the Dataverse gets attached
to. Defaults to ``:root``.
Returns
-------
requests.Response
Response object of requests library.
"""
if not parent:
raise DataverseNotFoundError(
'Dataverse {} not found. No parent dataverse passed to '
'`create_dataverse()`.'.format(identifier)
)
query_str = '/dataverses/{0}'.format(parent)
resp = self.post_request(query_str, metadata, auth)
if resp.status_code == 404:
error_msg = resp.json()['message']
raise DataverseNotFoundError(
'ERROR: HTTP 404 - Dataverse {0} was not found. MSG: '.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 : string
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
-------
requests.Response
Response object of requests library.
"""
query_str = '/dataverses/{0}/actions/:publish'.format(identifier)
resp = self.post_request(query_str, 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 {} 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 {} published.'.format(identifier))
return resp
def delete_dataverse(self, identifier, auth=True):
"""Delete dataverse by alias or id.
HTTP Request:
.. code-block:: bash
DELETE http://$SERVER/api/dataverses/$id
Status Code:
200: Dataverse deleted
Parameters
----------
identifier : string
Can either be a dataverse id (long) or a dataverse alias (more
robust).
Returns
-------
requests.Response
Response object of requests library.
"""
query_str = '/dataverses/{0}'.format(identifier)
resp = self.delete_request(query_str, 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 {} deleted.'.format(identifier))
return resp
def get_dataset(self, identifier, 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 : string
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
-------
requests.Response
Response object of requests library.
"""
if is_pid:
query_str = '/datasets/:persistentId/?persistentId={0}'.format(
identifier)
else:
query_str = '/datasets/{0}'.format(identifier)
resp = self.get_request(query_str, auth=auth)
return resp
def get_dataset_export(self, pid, export_format):
"""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 : string
Persistent identifier of the dataset. (e.g. ``doi:10.11587/8H3N93``).
export_format : string
Export format as a string. Formats: ``ddi``, ``oai_ddi``,
``dcterms``, ``oai_dc``, ``schema.org``, ``dataverse_json``.
Returns
-------
requests.Response
Response object of requests library.
"""
query_str = '/datasets/export?exporter={0}&persistentId={1}'.format(
export_format, pid)
resp = self.get_request(query_str)
return resp
def create_dataset(self, dataverse, metadata, 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
Parameters
----------
dataverse : string
"alias" of the dataverse (e.g. ``root``) or the database id of the
dataverse (e.g. ``1``)
metadata : string
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
-------
requests.Response
Response object of requests library.
Todo
-------
Link Dataset finch1.json
"""
query_str = '/dataverses/{0}/datasets'.format(dataverse)
resp = self.post_request(query_str, 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 - Delete Dataset unauthorized. MSG: '
''.format(error_msg)
)
elif resp.status_code == 201:
identifier = resp.json()['data']['persistentId']
print('Dataset {} created.'.format(identifier))
return resp
def publish_dataset(self, pid, 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 : string
Persistent identifier of the dataset (e.g.
``doi:10.11587/8H3N93``).
type : string
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
-------
requests.Response
Response object of requests library.
"""
query_str = '/datasets/:persistentId/actions/:publish'
query_str += '?persistentId={0}&type={1}'.format(identifier, type)
resp = self.post_request(query_str, 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 == 401:
error_msg = resp.json()['message']
raise ApiAuthorizationError(
'ERROR: HTTP 401 - User not allowed to publish dataset {0}. '
'MSG: {1}'.format(identifier, error_msg))
elif resp.status_code == 200:
print('Dataset {} published'.format(identifier))
return resp
def delete_dataset(self, identifier, is_pid=True, auth=True):
"""Delete a dataset.
Delete the dataset whose id is passed
HTTP Request:
.. code-block:: bash
DELETE http://$SERVER/api/datasets/$id
Status Code:
200: dataset deleted
Parameters
----------
identifier : string
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
-------
requests.Response
Response object of requests library.
"""
if is_pid:
query_str = '/datasets/:persistentId/?persistentId={0}'.format(
identifier)
else:
query_str = '/datasets/{0}'.format(identifier)
resp = self.delete_request(query_str, 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: {}'.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 {} deleted'.format(identifier))
return resp
def edit_dataset_metadata(self, identifier, metadata, is_pid=True,
is_replace=False, auth=True):
"""Edit metadata of a given dataset.
`Offical documentation
<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 : string
Identifier of the dataset. Can be a Dataverse identifier or a
persistent identifier (e.g. ``doi:10.11587/8H3N93``).
metadata : string
Metadata of the Dataset as a json-formatted string.
is_pid : bool
``True`` to use persistent identifier. ``False``, if not.
is_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
-------
requests.Response
Response object of requests library.
Examples
-------
Get dataset metadata::
>>> data = api.get_dataset_metadata(doi, auth=True)
>>> resp = api.edit_dataset_metadata(doi, data, is_replace=True, auth=True)
>>> resp.status_code
200: metadata updated
"""
if is_pid:
query_str = '/datasets/:persistentId/editMetadata/?persistentId={0}'
''.format(identifier)
else:
query_str = '/datasets/editMetadata/{0}'.format(identifier)
params = {'replace': True} if is_replace else {}
resp = self.put_request(query_str, metadata, auth, params)
if resp.status_code == 401:
error_msg = resp.json()['message']
raise ApiAuthorizationError(
'ERROR: HTTP 401 - Updating metadata unauthorized. MSG: '
''.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 get_datafiles(self, pid, version='1'):
"""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 : string
Persistent identifier of the dataset. e.g. ``doi:10.11587/8H3N93``.
version : string
Version of dataset. Defaults to `1`.
Returns
-------
requests.Response
Response object of requests library.
"""
base_str = '/datasets/:persistentId/versions/'
query_str = base_str + '{0}/files?persistentId={1}'.format(
version, pid)
resp = self.get_request(query_str)
return resp
def get_datafile(self, identifier, is_pid=True):
"""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 : string
Identifier of the dataset. 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
-------
requests.Response
Response object of requests library.
"""
if is_pid:
query_str = '/access/datafile/{0}'.format(identifier)
else:
query_str = '/access/datafile/:persistentId/?persistentId={0}'
''.format(identifier)
resp = self.get_request(query_str)
return resp
def get_datafile_bundle(self, identifier):
"""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 : string
Identifier of the dataset.
Returns
-------
requests.Response
Response object of requests library.
"""
query_str = '/access/datafile/bundle/{0}'.format(identifier)
data = self.get_request(query_str)
return data
def upload_file(self, identifier, filename, 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