Skip to content

Commit 4d6186d

Browse files
committed
rework examples, especially the first one
1 parent 572d9c2 commit 4d6186d

File tree

7 files changed

+218
-46
lines changed

7 files changed

+218
-46
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ generated/
22
openapi.yaml
33
html
44
venv
5+
__pycache__

config.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22
"packageName": "elabapi_python",
33
"pythonPackageName": "elabapi_python",
44
"projectName": "elabapi-python",
5-
"packageVersion": "5.1.0",
5+
"packageVersion": "5.2.0",
66
"packageUrl": "https://github.com/elabftw/elabapi-python"
77
}

examples/00-getting-started.py

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
#!/usr/bin/env python
2+
3+
##############################################################################################
4+
# Welcome to the first example of using elabapi_python in a script #
5+
# This file is heavily commented and will show you various examples of using the API library #
6+
##############################################################################################
7+
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
17+
import elabapi_python
18+
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()
28+
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
47+
48+
# Note:
49+
# 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
50+
51+
def part1():
52+
##############################
53+
# Part 1: the /info endpoint #
54+
##############################
55+
# Doc: https://doc.elabftw.net/api/v2/#/Info/get-info
56+
# Let's start with a very simple endpoint: /info. It only has a GET method and replies with information about the instance.
57+
# It's an easy way to validate if all is working as expected.
58+
# Everytime we want to use an endpoint, we need to create the corresponding object and give it the api_client (which itself holds the configuration)
59+
info_client = elabapi_python.InfoApi(api_client)
60+
api_response = info_client.get_info()
61+
# Print the full response
62+
print("\n------------------------ START PART 1 ------------------------\n")
63+
print("[request] GET /info")
64+
pprint(api_response)
65+
print("")
66+
# Example usage
67+
print(f"[*] The instance at {API_HOST} has {api_response.teams_count} teams and {api_response.all_users_count} users.")
68+
print(f"[*] Total size of uploaded files: {api_response.uploads_filesize_sum_formatted}")
69+
print("\n------------------------ END PART 1 ------------------------\n")
70+
71+
def part2():
72+
####################################
73+
# Part 2: manipulating experiments #
74+
####################################
75+
# For this we need an "experiments" endpoint client object
76+
exp_client = elabapi_python.ExperimentsApi(api_client)
77+
78+
print("\n------------------------ START PART 2 ------------------------\n")
79+
print("[request] POST /experiments")
80+
# Let's create our first experiment through the API
81+
# Doc: https://doc.elabftw.net/api/v2/#/Experiments/post-experiment
82+
# We will use the post_experiment_with_http_info() method so we can have something in the response
83+
# If you use post_experiment(), it works but doesn't send back the response headers (which contain the ID of the newly created entry)
84+
# This method returns a tuple with 3 components, so we assign them to 3 variables
85+
response_data, status_code, headers = exp_client.post_experiment_with_http_info()
86+
# the Location response header will point to the newly created entry
87+
location = headers.get('Location')
88+
# extract the ID as an integer from the Location string: it is simply the last part of the URL
89+
exp_id = int(location.split('/').pop())
90+
# A status code of 201 means the entry was created
91+
if status_code == 201:
92+
print(f"[*] We created an experiment. The status code is {status_code} and the experiment is at: {location}")
93+
94+
# Let's try and delete it now!
95+
print(f"[request] DELETE /experiments/{exp_id}")
96+
response_data, status_code, headers = exp_client.delete_experiment_with_http_info(exp_id)
97+
if status_code == 204:
98+
print(f"[*] We deleted the experiment with id: {exp_id}")
99+
100+
# Ok, now we will create another experiment but this time we will provide some information during creation
101+
# This dictionary will hold the values that we send during creation
102+
exp_data = {
103+
"title": "This experiment was created from the API with Python!",
104+
"body": "<h1>Some title</h1><p>Some content.<p>",
105+
"tags": ["created from api", "pythonftw", "tests"],
106+
}
107+
# Now we send the request with the "body" keyword parameter set to exp_data
108+
print("[request] POST /experiments")
109+
response_data, status_code, headers = exp_client.post_experiment_with_http_info(body=exp_data)
110+
exp_id = int(headers.get('Location').split('/').pop())
111+
if status_code == 201:
112+
print(f"[*] We created another experiment with ID: {exp_id}")
113+
114+
# Let's verify that the title is correct. For that, we will GET the experiment to read it
115+
# Note that this time we do not use the _with_http_info function, but simply get_experiment()
116+
# It returns a pre-processed Entity object
117+
print(f"[request] GET /experiments/{exp_id}")
118+
experiment = exp_client.get_experiment(exp_id)
119+
print(f"[*] Our experiment has this title: {experiment.title}")
120+
121+
# Ok let's change that title now, with a PATCH request
122+
print(f"[request] PATCH /experiments/{exp_id}")
123+
experiment = exp_client.patch_experiment(exp_id, body={"title": "Now the title was changed from the API!"})
124+
print(f"[*] Our experiment now has this title: {experiment.title}")
125+
print(f"[*] Check it out on the web interface: {experiment.sharelink}")
126+
127+
print("\n------------------------ END PART 2 ------------------------\n")
128+
129+
130+
# This is where the script really starts: we simply call the different functions representing parts of this tutorial one after the other
131+
part1()
132+
part2()

examples/00-read-items.py

Lines changed: 0 additions & 43 deletions
This file was deleted.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#!/usr/bin/env python
2+
3+
###################################################################################################
4+
# In this example script, we show you how to manage extra fields through the "metadata" attribute #
5+
###################################################################################################
6+
7+
from pprint import pprint
8+
import elabapi_python
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
11+
from client import api_client
12+
13+
# Note:
14+
# 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
15+
16+
######################################################
17+
# Part 1: creating a Resource with specific metadata #
18+
######################################################
19+
# Doc: https://doc.elabftw.net/api/v2/#/Items/post-item
20+
# Start by creating our api object to interact with /items endpoint
21+
items_client = elabapi_python.ItemsApi(api_client)
22+
23+
# Now define our metadata: in this case, two fields of type number, with units
24+
metadata = {
25+
"extra_fields": {
26+
"Laser power": {
27+
"type": "number",
28+
"value": "50",
29+
"units": ["mW", "W", "MW"],
30+
"unit": "MW",
31+
},
32+
"Illumination time": {
33+
"type": "number",
34+
"value": "85",
35+
"units": ["min", "sec", "hour"],
36+
"unit": "min",
37+
},
38+
},
39+
}
40+
41+
# now create a Resource with this metadata
42+
data = {
43+
"title": "Resource with metadata created from API",
44+
"metadata": metadata,
45+
}
46+
response_data, status_code, headers = items_client.post_item_with_http_info(body=data)
47+
item_id = int(headers.get('Location').split('/').pop())
48+
if status_code == 201:
49+
print(f"[*] We created a Resource with ID: {item_id}")

examples/client.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# This file is there to avoid having to replicate the same code in all examples
2+
3+
# We will use the standard "os" module to read values from environment
4+
import os
5+
import elabapi_python
6+
7+
# START CONFIG
8+
# Basic configuration: Api Key and Host URL
9+
# Get the Api Key from the environment or use the default development value
10+
API_KEY = os.getenv('API_KEY') or 'apiKey4Test'
11+
# Get the server address from the environment or use the default development value
12+
API_HOST = os.getenv('API_HOST') or 'https://elab.local:3148/api/v2'
13+
14+
# Initialize a configuration object from the library
15+
configuration = elabapi_python.Configuration()
16+
17+
# Set the host
18+
configuration.host = API_HOST
19+
# Verify the TLS certificate validity: should be set to True in production
20+
configuration.verify_ssl = False
21+
# For convenience, mask the warnings about skipping TLS verification
22+
if not configuration.verify_ssl:
23+
import urllib3
24+
urllib3.disable_warnings(category=urllib3.exceptions.InsecureRequestWarning)
25+
26+
# Set this flag to True to get more verbose output
27+
configuration.debug = False
28+
29+
# Create an API client object with our configuration
30+
api_client = elabapi_python.ApiClient(configuration)
31+
32+
# Set the Api Key in Authorization header
33+
api_client.set_default_header(header_name='Authorization', header_value=API_KEY)

helper.sh

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
# the docker image used to generate the client code
99
# pinning version to avoid unexpected bugs
1010
# see https://github.com/swagger-api/swagger-codegen/releases for updating version below
11-
docker_image="swaggerapi/swagger-codegen-cli-v3:3.0.54"
11+
docker_image="swaggerapi/swagger-codegen-cli-v3:3.0.68"
1212
# where to grab the definition file
1313
openapi_yaml_url="https://raw.githubusercontent.com/elabftw/elabftw/master/apidoc/v2/openapi.yaml"
1414
# folder with the generated python code
@@ -60,7 +60,7 @@ function publish {
6060

6161
function install-dev {
6262
cd "$lib" || exit 1
63-
python setup.py develop --user
63+
pip install -e generated
6464
cd ..
6565
}
6666

0 commit comments

Comments
 (0)