Skip to content

Commit e4f39d5

Browse files
committed
Merge branch 'master' of github.com:elabftw/elabapi-python
* 'master' of github.com:elabftw/elabapi-python: chore: examples: update using local client module & fix some examples (#43)
2 parents d004330 + 909a58b commit e4f39d5

22 files changed

+135
-456
lines changed

examples/00-getting-started.py

Lines changed: 6 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -5,45 +5,14 @@
55
# This file is heavily commented and will show you various examples of using the API library #
66
##############################################################################################
77

8-
# We will use the standard "os" module to read values from environment
9-
import os
10-
11-
# and this one to pretty print python object
12-
from pprint import pprint
13-
14-
# You must have elabapi-python installed so it can be imported
15-
# This line will make the library available in our script
16-
# Install it with: pip install elabapi-python
178
import elabapi_python
189

19-
# START CONFIG
20-
# Basic configuration: Api Key and Host URL
21-
# Get the Api Key from the environment or use the default development value
22-
API_KEY = os.getenv('API_KEY') or 'apiKey4Test'
23-
# Get the server address from the environment or use the default development value
24-
API_HOST = os.getenv('API_HOST') or 'https://elab.local:3148/api/v2'
25-
26-
# Initialize a configuration object from the library
27-
configuration = elabapi_python.Configuration()
10+
# first, use the locally defined client.py module to get the api_client object. (see /examples/client.py)
11+
# it is fully configured and ready to be used to instantiate api objects
12+
from client import api_client
2813

29-
# Set the host
30-
configuration.host = API_HOST
31-
# Verify the TLS certificate validity: should be set to True in production
32-
configuration.verify_ssl = False
33-
# For convenience, mask the warnings about skipping TLS verification
34-
if not configuration.verify_ssl:
35-
import urllib3
36-
urllib3.disable_warnings(category=urllib3.exceptions.InsecureRequestWarning)
37-
38-
# Set this flag to True to get more verbose output
39-
configuration.debug = False
40-
41-
# Create an API client object with our configuration
42-
api_client = elabapi_python.ApiClient(configuration)
43-
44-
# Set the Api Key in Authorization header
45-
api_client.set_default_header(header_name='Authorization', header_value=API_KEY)
46-
# END CONFIG
14+
# add pprint to pretty print python objects
15+
from pprint import pprint
4716

4817
# Note:
4918
# In order to make it easier to run only specific parts, the parts are grouped in functions that are called at the end of the script
@@ -64,7 +33,7 @@ def part1():
6433
pprint(api_response)
6534
print("")
6635
# Example usage
67-
print(f"[*] The instance at {API_HOST} has {api_response.teams_count} teams and {api_response.all_users_count} users.")
36+
print(f"[*] The instance at {api_client.configuration.host} has {api_response.teams_count} teams and {api_response.all_users_count} users.")
6837
print(f"[*] Total size of uploaded files: {api_response.uploads_filesize_sum_formatted}")
6938
print("\n------------------------ END PART 1 ------------------------\n")
7039

examples/001-manipulating-metadata.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,11 @@
55
###################################################################################################
66

77
import elabapi_python
8-
9-
# use the locally defined client.py module to get the api_client object, fully configured and ready to be used to instantiate api objects
108
from client import api_client
119

12-
# Note:
13-
# In order to make it easier to run only specific parts, the parts are grouped in functions that are called at the end of the script
14-
15-
######################################################
16-
# Part 1: creating a Resource with specific metadata #
17-
######################################################
10+
##############################################
11+
# Creating a Resource with specific metadata #
12+
##############################################
1813
# Doc: https://doc.elabftw.net/api/v2/#/Items/post-item
1914
# Start by creating our api object to interact with /items endpoint
2015
items_client = elabapi_python.ItemsApi(api_client)

examples/002-extra-field-to-column.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,13 @@
66

77
import elabapi_python
88
import json
9-
10-
# use the locally defined client.py module to get the api_client object, fully configured and ready to be used to instantiate api objects
119
from client import api_client
1210

1311
# Start by creating our api object to interact with /items endpoint
1412
items_client = elabapi_python.ItemsApi(api_client)
1513

16-
# In this example, this corresponds to "Chemicals". Adapt to your instance.
17-
RESOURCE_CATEGORY_ID = 5
14+
# In this example, this corresponds to "Antibody". Adapt to your instance.
15+
RESOURCE_CATEGORY_ID = 3
1816
# this value is the same for all eLabFTW instances
1917
CURRENCY_EUROS = 4
2018

examples/01-download-timestamp-archive.py

Lines changed: 6 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,14 @@
11
#!/usr/bin/env python
22
import datetime
33
import elabapi_python
4+
from client import api_client
45

5-
#########################
6-
# CONFIG #
7-
#########################
8-
API_HOST_URL = 'https://elab.local:3148/api/v2'
9-
# replace with your api key
10-
API_KEY = 'apiKey4Test'
11-
# number of days to look back
12-
PERIOD_IN_DAYS = 7
13-
#########################
14-
# END CONFIG #
15-
#########################
16-
17-
# Configure the api client
18-
configuration = elabapi_python.Configuration()
19-
configuration.api_key['api_key'] = API_KEY
20-
configuration.api_key_prefix['api_key'] = 'Authorization'
21-
configuration.host = API_HOST_URL
22-
configuration.debug = False
23-
configuration.verify_ssl = False
6+
##################################################################################
7+
# In this example script, we will download timestamps archives from experiments. #
8+
##################################################################################
249

25-
# create an instance of the API class
26-
api_client = elabapi_python.ApiClient(configuration)
27-
# fix issue with Authorization header not being properly set by the generated lib
28-
api_client.set_default_header(header_name='Authorization', header_value=API_KEY)
10+
# define number of days to look back
11+
PERIOD_IN_DAYS = 7
2912

3013
# create an instance of Experiments and another for Uploads
3114
experimentsApi = elabapi_python.ExperimentsApi(api_client)
Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,9 @@
11
#!/usr/bin/env python
22
import elabapi_python
3+
from client import api_client
34

4-
#########################
5-
# CONFIG #
6-
#########################
7-
API_HOST_URL = 'https://elab.local:3148/api/v2'
8-
# replace with your api key
9-
API_KEY = 'apiKey4Test'
10-
#########################
11-
# END CONFIG #
12-
#########################
13-
14-
# Configure the api client
15-
configuration = elabapi_python.Configuration()
16-
configuration.api_key['api_key'] = API_KEY
17-
configuration.api_key_prefix['api_key'] = 'Authorization'
18-
configuration.host = API_HOST_URL
19-
configuration.debug = False
20-
configuration.verify_ssl = False
21-
22-
# create an instance of the API class
23-
api_client = elabapi_python.ApiClient(configuration)
24-
# fix issue with Authorization header not being properly set by the generated lib
25-
api_client.set_default_header(header_name='Authorization', header_value=API_KEY)
5+
# define which category's items are patched
6+
RESOURCE_CATEGORY_ID = 3
267

278
# Synchronize metadata of the item_type with existing items
289
# See: https://github.com/elabftw/elabftw/issues/3524
@@ -32,9 +13,8 @@
3213

3314
metadata = '{"elabftw": {"extra_fields_groups": [{"id": 1,"name": "Drug settings"},{"id": 2,"name": "Mice info"}]},"extra_fields": {"Drug addition": {"type": "datetime-local","value": "","group_id": 1,"required": true,"description": "Time when drug is added"},"Drug concentration": {"type": "number","unit": "mM","units": ["mM","μM","nM"],"value": "","group_id": 1,"required": true},"Mouse sex": {"type": "select","value": "Male","options": ["Male","Female"],"group_id": 2}}}'
3415

35-
for item in itemsApi.read_items(cat=1, limit=9999):
16+
for item in itemsApi.read_items(cat=RESOURCE_CATEGORY_ID, limit=9999):
3617
# skip items with metadata already
3718
if not item.metadata:
3819
print(f'Patching item {item.id}')
3920
itemsApi.patch_item(item.id, body={'metadata': metadata})
40-
Lines changed: 48 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,58 @@
11
#!/usr/bin/env python
2+
3+
#################################################################################
4+
# In this example script, we will upload a file to an experiment and delete it. #
5+
# You can comment the 'delete' part to see results in your experiment. #
6+
#################################################################################
7+
8+
# Doc: https://doc.elabftw.net/api/v2/#/Uploads
9+
10+
# part 1 (upload_file_to_experiment) will upload a file to a target experiment.
11+
# part 2 (download_matching_uploads_locally) will download locally a file from an eLabFTW experiment.
12+
# part 3 (cleanup) will remove the files from both the experiment and locally.
213
import os
314
import elabapi_python
4-
5-
#########################
6-
# CONFIG #
7-
#########################
8-
API_HOST_URL = 'https://elab.local:3148/api/v2'
9-
# replace with your api key
10-
API_KEY = 'apiKey4Test'
11-
#########################
12-
# END CONFIG #
13-
#########################
14-
15-
# Configure the api client
16-
configuration = elabapi_python.Configuration()
17-
configuration.api_key['api_key'] = API_KEY
18-
configuration.api_key_prefix['api_key'] = 'Authorization'
19-
configuration.host = API_HOST_URL
20-
configuration.debug = False
21-
configuration.verify_ssl = False
22-
23-
# create an instance of the API class
24-
api_client = elabapi_python.ApiClient(configuration)
25-
# fix issue with Authorization header not being properly set by the generated lib
26-
api_client.set_default_header(header_name='Authorization', header_value=API_KEY)
15+
from client import api_client
2716

2817
# create an instance of Experiments and another for Uploads
2918
experimentsApi = elabapi_python.ExperimentsApi(api_client)
3019
uploadsApi = elabapi_python.UploadsApi(api_client)
3120

32-
# get experiment with ID 256
33-
exp = experimentsApi.get_experiment(256)
34-
# upload the file 'README.md' present in the current folder
35-
uploadsApi.post_upload('experiments', 256, file='README.md', comment='Uploaded with APIv2')
36-
# display id, name and comment of the uploaded files
37-
for upload in uploadsApi.read_uploads('experiments', exp.id):
38-
print(upload.id, upload.real_name, upload.comment)
39-
# get and save file
40-
with open('README.downloaded_with_api.md', 'wb') as file:
41-
# the _preload_content flag is necessary so the api_client doesn't try and deserialize the response
42-
file.write(uploadsApi.read_upload('experiments', 256, upload.id, format='binary', _preload_content=False).data)
21+
# define the target experiment
22+
EXPERIMENT_ID = 210
23+
# prepare the file. We'll use the 'README.md' present in current folder
24+
SOURCE_FILE = "README.md"
25+
# local downloads for the script
26+
DOWNLOADED_FILENAME = "README.downloaded_with_api.md"
27+
28+
exp = experimentsApi.get_experiment(EXPERIMENT_ID)
29+
30+
# --- part 1: Upload file to experiment ---
31+
def upload_file_to_experiment():
32+
uploadsApi.post_upload('experiments', EXPERIMENT_ID, file=SOURCE_FILE, comment='Uploaded with APIv2')
33+
34+
# --- part 2: Download uploads locally ---
35+
def download_matching_uploads_locally():
36+
# display id, name and comment of the uploaded files and download them locally
37+
for upload in uploadsApi.read_uploads('experiments', exp.id):
38+
print(upload.id, upload.real_name, upload.comment, upload.state)
39+
# get and save file
40+
with open(DOWNLOADED_FILENAME, 'wb') as file:
41+
# the _preload_content flag is necessary so the api_client doesn't try and deserialize the response
42+
file.write(uploadsApi.read_upload('experiments', EXPERIMENT_ID, upload.id, format='binary', _preload_content=False).data)
43+
44+
# --- part 3: delete the downloaded file ---
45+
def cleanup():
4346
# delete all the files where the name is 'README.md'
44-
if upload.real_name == 'README.md':
45-
uploadsApi.delete_upload('experiments', 256, upload.id)
47+
for upload in uploadsApi.read_uploads('experiments', exp.id):
48+
if upload.real_name == SOURCE_FILE:
49+
uploadsApi.delete_upload('experiments', EXPERIMENT_ID, upload.id)
50+
# cleanup: delete the downloaded file
51+
try:
52+
os.remove(DOWNLOADED_FILENAME)
53+
except FileNotFoundError:
54+
pass
4655

47-
# cleanup: delete the downloaded file
48-
os.remove('README.downloaded_with_api.md')
56+
upload_file_to_experiment()
57+
download_matching_uploads_locally()
58+
cleanup()

examples/04-create-teamgroup-add-user.py

Lines changed: 1 addition & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,6 @@
11
#!/usr/bin/env python
22
import elabapi_python
3-
4-
#########################
5-
# CONFIG #
6-
#########################
7-
API_HOST_URL = 'https://elab.local:3148/api/v2'
8-
# replace with your api key
9-
API_KEY = 'apiKey4Test'
10-
#########################
11-
# END CONFIG #
12-
#########################
13-
14-
# Configure the api client
15-
configuration = elabapi_python.Configuration()
16-
configuration.api_key['api_key'] = API_KEY
17-
configuration.api_key_prefix['api_key'] = 'Authorization'
18-
configuration.host = API_HOST_URL
19-
configuration.debug = False
20-
configuration.verify_ssl = False
21-
22-
# create an instance of the API class
23-
api_client = elabapi_python.ApiClient(configuration)
24-
# fix issue with Authorization header not being properly set by the generated lib
25-
api_client.set_default_header(header_name='Authorization', header_value=API_KEY)
3+
from client import api_client
264

275
# Load teamgroup api
286
teamgroupsApi = elabapi_python.TeamgroupsApi(api_client)

examples/05-create-modify-item.py

Lines changed: 2 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,13 @@
11
#!/usr/bin/env python
22
import elabapi_python
3-
4-
#########################
5-
# CONFIG #
6-
#########################
7-
API_HOST_URL = 'https://elab.local:3148/api/v2'
8-
# replace with your api key
9-
API_KEY = 'apiKey4Test'
10-
#########################
11-
# END CONFIG #
12-
#########################
13-
14-
# Configure the api client
15-
configuration = elabapi_python.Configuration()
16-
configuration.api_key['api_key'] = API_KEY
17-
configuration.api_key_prefix['api_key'] = 'Authorization'
18-
configuration.host = API_HOST_URL
19-
configuration.debug = False
20-
configuration.verify_ssl = False
21-
22-
# create an instance of the API class
23-
api_client = elabapi_python.ApiClient(configuration)
24-
# fix issue with Authorization header not being properly set by the generated lib
25-
api_client.set_default_header(header_name='Authorization', header_value=API_KEY)
3+
from client import api_client
264

275
# Load items api
286
itemsApi = elabapi_python.ItemsApi(api_client)
297

308
# Create an item with the category_id 1 (items_types ID = 1)
319
targetCategory = 1
32-
response = itemsApi.post_item_with_http_info(body={'category_id': targetCategory, 'tags': ['some tag', 'another tag']})
10+
response = itemsApi.post_item_with_http_info(body={'category': targetCategory, 'tags': ['some tag', 'another tag']})
3311
locationHeaderInResponse = response[2].get('Location')
3412
print(f'The newly created item is here: {locationHeaderInResponse}')
3513
itemId = int(locationHeaderInResponse.split('/').pop())

examples/06-create-users.py

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,7 @@
11
#!/usr/bin/env python
22
import elabapi_python
33

4-
#########################
5-
# CONFIG #
6-
#########################
7-
API_HOST_URL = 'https://elab.local:3148/api/v2'
8-
# replace with your api key
9-
API_KEY = 'apiKey4Test'
10-
#########################
11-
# END CONFIG #
12-
#########################
13-
14-
# Configure the api client
15-
configuration = elabapi_python.Configuration()
16-
configuration.api_key['api_key'] = API_KEY
17-
configuration.api_key_prefix['api_key'] = 'Authorization'
18-
configuration.host = API_HOST_URL
19-
configuration.debug = False
20-
configuration.verify_ssl = False
21-
22-
# create an instance of the API class
23-
api_client = elabapi_python.ApiClient(configuration)
24-
# fix issue with Authorization header not being properly set by the generated lib
25-
api_client.set_default_header(header_name='Authorization', header_value=API_KEY)
4+
from client import api_client
265

276
#### SCRIPT START #####
287
# Description: create users in batch

0 commit comments

Comments
 (0)