Skip to content

requests

REST API Requests ModuleLink

Provides a unified interface for communicating with the PlantDB REST API, handling authentication, data retrieval, and file transfers. It abstracts HTTP request details, allowing client code to focus on business logic.

Key FeaturesLink

  • Centralized make_api_request supporting GET, POST, PUT, DELETE with timeout, SSL verification, and custom headers.
  • Convenience helpers for authentication (login, logout, token validation/refresh).
  • Utilities for managing scans, images, archives, and dataset files.
  • Streamed download/upload support with timing for performance monitoring.

Usage ExamplesLink

>>> from plantdb.client.rest_api.requests import request_login, request_scan_image
>>> login = request_login('localhost', 'admin', 'admin', port=5000)
>>> content_type, _, img_bytes = request_scan_image(
...     'localhost', 'real_plant', 'images', '00000_rgb',
...     port=5000, session_token=login['access_token'])
>>> # `img_bytes` now contains the raw image data.

make_api_request Link

make_api_request(url, method='GET', params=None, json_data=None, allow_redirects=True, **kwargs)

Function to make an API request with various HTTP methods and options.

Parameters:

Name Type Description Default

url Link

str

The URL for the API endpoint.

required

method Link

(GET, POST, PUT, DELETE)

The HTTP method to use. Default is 'GET'.

'GET'

params Link

dict

Dictionary of query parameters to append to the URL.

None

json_data Link

dict

JSON payload to send in the body of the request for 'POST' and 'PUT' methods.

None

allow_redirects Link

bool

Whether to allow redirects. Default is True.

True

Other Parameters:

Name Type Description
header dict

The HTTP headers to send in the request. Default is None.

files dict

Additional files to send in the request. Default is None.

data dict, list, or bytes

The data to send in the request. Default is None.

timeout int

Timeout to use for the request. Default is 5 seconds.

stream bool

Flag indicating whether to stream the request. Default is False.

session_token str

The PlantDB REST API session token of the user. It should be supplied for every request that requires authentication on the server-side.

Returns:

Type Description
Response

The response object from the API request.

Raises:

Type Description
ValueError

If an unsupported HTTP method is provided.

SSLError

If there's an SSL error during the request.

RequestException

For any other exception raised by the underlying requests library.

Notes

This function is designed to handle various HTTP methods (GET, POST, PUT, DELETE) and provides a unified interface for making API requests. It supports SSL verification and allows for custom parameters and JSON data to be sent with the request. It passes keyword arguments to the underlying requests library.

Examples:

>>> from plantdb.client.rest_api.requests import make_api_request
>>> from plantdb.client.rest_api.urls import login_url
>>> response = make_api_request(login_url('localhost', port=5000), "POST", json_data={'username': 'admin', 'password': 'admin'})
>>> access_token, refresh_token = response.json()['access_token'], response.json()['refresh_token']
>>> user = response.json()['user']
Source code in plantdb/client/rest_api/requests.py
 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
def make_api_request(url, method="GET", params=None, json_data=None,
                     allow_redirects=True, **kwargs):
    """Function to make an API request with various HTTP methods and options.

    Parameters
    ----------
    url : str
        The URL for the API endpoint.
    method : {'GET', 'POST', 'PUT', 'DELETE'}, optional
        The HTTP method to use. Default is 'GET'.
    params : dict, optional
        Dictionary of query parameters to append to the URL.
    json_data : dict, optional
        JSON payload to send in the body of the request for 'POST' and 'PUT' methods.
    allow_redirects : bool, optional
        Whether to allow redirects. Default is True.

    Other Parameters
    ----------------
    header : dict
        The HTTP headers to send in the request. Default is None.
    files : dict
        Additional files to send in the request. Default is None.
    data : dict, list, or bytes
        The data to send in the request. Default is None.
    timeout : int
        Timeout to use for the request. Default is 5 seconds.
    stream : bool
        Flag indicating whether to stream the request. Default is False.
    session_token : str
        The PlantDB REST API session token of the user.
        It should be supplied for every request that requires authentication on the server-side.

    Returns
    -------
    requests.Response
        The response object from the API request.

    Raises
    ------
    ValueError
        If an unsupported HTTP method is provided.
    requests.exceptions.SSLError
        If there's an SSL error during the request.
    requests.exceptions.RequestException
        For any other exception raised by the underlying `requests` library.

    Notes
    -----
    This function is designed to handle various HTTP methods (GET, POST, PUT, DELETE) and provides a unified interface for making API requests. It supports SSL verification and allows for custom parameters and JSON data to be sent with the request.
    It passes keyword arguments to the underlying `requests` library.

    Examples
    --------
    >>> from plantdb.client.rest_api.requests import make_api_request
    >>> from plantdb.client.rest_api.urls import login_url
    >>> response = make_api_request(login_url('localhost', port=5000), "POST", json_data={'username': 'admin', 'password': 'admin'})
    >>> access_token, refresh_token = response.json()['access_token'], response.json()['refresh_token']
    >>> user = response.json()['user']
    """
    requests_kwargs = {}
    requests_kwargs['params'] = params
    requests_kwargs['allow_redirects'] = allow_redirects

    # Add a default timeout of 5 seconds if not provided
    requests_kwargs['timeout'] = kwargs.get('timeout', 5.0)

    # Prepare SSL/TLS verification; if CERT_PATH is supplied, use it,
    # otherwise default to requests' built‑in verification
    requests_kwargs['verify'] = os.getenv('CERT_PATH', True)

    requests_kwargs['headers'] = kwargs.get('headers', {})
    # If a session token is supplied, add it to the Authorization header
    if 'session_token' in kwargs:
        requests_kwargs['headers'].update({'Authorization': f"Bearer {kwargs.get('session_token')}"})

    # Normalize the HTTP method name to uppercase for comparison
    method = method.upper()

    # Add an empty JSON payload to forces the requests library to add the correct `Content‑Type: application/json` header
    if not json_data:
        json_data = {}

    try:
        if method.upper() == "GET":
            # GET: retrieve a resource, may include query params
            response = requests.get(url, **requests_kwargs)
        elif method.upper() == "POST":
            # POST: send data (json_data or raw binary)
            response = requests.post(url, json=json_data, **requests_kwargs)
        elif method.upper() == "PUT":
            # PUT: replace or update a resource
            response = requests.put(url, json=json_data, **requests_kwargs)
        elif method.upper() == "DELETE":
            # DELETE: remove a resource
            response = requests.delete(url, **requests_kwargs)
        else:
            # Unsupported HTTP method
            raise ValueError(f"Unsupported HTTP method: {method}")

        response.raise_for_status()  # Raise exception for 4XX/5XX responses
        return response
    except requests.exceptions.SSLError as e:
        logger.error(f"SSL Error: {e}")
        raise e from e
    except requests.exceptions.RequestException as e:
        logger.error(f"Request Error: {e}")
        raise e from e

request_api_token Link

request_api_token(host, token_exp, datasets, **kwargs)

Refresh a token by making a POST request to the token refresh endpoint.

Parameters:

Name Type Description Default

host Link

str

The hostname or base URL used to construct the refresh endpoint.

required

token_exp Link

int

The expiration duration of the API token in seconds.

required

datasets Link

list[dict[str, Tuple[Permissions]]

A dictionary where the keys are dataset names, and the values are either a tuple of Permission instances or a single Permission instance defining the access levels for each dataset.

required

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
dict

The token refresh data from the response, if successful.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_login
>>> from plantdb.client.rest_api.requests import request_api_token
>>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
>>> api_token_data = request_api_token('localhost', 3600, {"Dataset_A": ('read', 'write', 'create')}, port=5000, session_token=login_data['access_token'])
>>> api_token = api_token_data['api_token']
>>> print(api_token)
Source code in plantdb/client/rest_api/requests.py
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
def request_api_token(host, token_exp, datasets, **kwargs) -> dict:
    """Refresh a token by making a POST request to the token refresh endpoint.

    Parameters
    ----------
    host : str
        The hostname or base URL used to construct the refresh endpoint.
    token_exp : int
        The expiration duration of the API token in seconds.
    datasets : list[dict[str, Tuple[Permissions]]
        A dictionary where the keys are dataset names, and the values are either
        a tuple of `Permission` instances or a single `Permission` instance
        defining the access levels for each dataset.


    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    dict
        The token refresh data from the response, if successful.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_login
    >>> from plantdb.client.rest_api.requests import request_api_token
    >>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
    >>> api_token_data = request_api_token('localhost', 3600, {"Dataset_A": ('read', 'write', 'create')}, port=5000, session_token=login_data['access_token'])
    >>> api_token = api_token_data['api_token']
    >>> print(api_token)
    """
    url = api_token_url(host, **kwargs)
    # Extract the payload arguments (they are optional so we provide sensible defaults)
    payload = {"datasets": datasets, "token_exp": token_exp}
    return make_api_request(url, method="POST", json_data=payload,
                            session_token=kwargs.get('session_token', None)).json()

request_archive_download Link

request_archive_download(host, scan_id, out_dir=None, **kwargs)

Downloads a scan archive file from a defined dataset based on the specified API parameters.

This function fetches a scan archive in stream mode from a remote API. The archive is expected to be in the form of a binary content stream. The success of the operation is determined by the HTTP response received from the API.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

scan_id Link

str

The name of the dataset from which the scan archive file is to be downloaded.

required

out_dir Link

str or Path

A path to the directory where to save the archive.

None

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to PLANTDB_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

timeout int

A timeout, in seconds, to succeed the download request. Defaults to 10.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
BytesIO or str

A BytesIO object containing the binary content of the downloaded scan archive. A path to the downloaded file, if a directory path is specified.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_archive_download
>>> request_archive_download('localhost', "arabidopsis000", out_dir='/tmp', port=5000)
('/tmp/arabidopsis000.zip', 'Download completed in 0.05 seconds.')
Source code in plantdb/client/rest_api/requests.py
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
def request_archive_download(host, scan_id, out_dir=None, **kwargs):
    """Downloads a scan archive file from a defined dataset based on the specified API parameters.

    This function fetches a scan archive in stream mode from a remote API. The archive
    is expected to be in the form of a binary content stream. The success of the
    operation is determined by the HTTP response received from the API.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str
        The name of the dataset from which the scan archive file is to be downloaded.
    out_dir : str or pathlib.Path, optional
        A path to the directory where to save the archive.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``PLANTDB_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    timeout : int, optional
        A timeout, in seconds, to succeed the download request. Defaults to ``10``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    BytesIO or str
        A `BytesIO` object containing the binary content of the downloaded scan archive.
        A path to the downloaded file, if a directory path is specified.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_archive_download
    >>> request_archive_download('localhost', "arabidopsis000", out_dir='/tmp', port=5000)
    ('/tmp/arabidopsis000.zip', 'Download completed in 0.05 seconds.')
    """
    import time
    # Construct API URL for archive download using dataset name and optional parameters
    url = archive_url(host, scan_id, **kwargs)

    request_kwargs = {
        'session_token': kwargs.get('session_token', None),
        'timeout': kwargs.get('timeout', 10),
    }

    # Track download duration for performance monitoring
    start_time = time.time()  # Start timing
    # Make streaming API request with configurable timeout and optional certificate
    response = make_api_request(url, stream=True, **request_kwargs)

    end_time = time.time()  # End timing
    duration = end_time - start_time
    msg = f"Download completed in {duration:.2f} seconds."

    if out_dir is not None:
        # Save archive to specified directory with dataset name as filename
        out_dir = Path(out_dir) / f"{scan_id}.zip"
        with open(out_dir, "wb") as archive_file:
            archive_file.write(response.content)
        return f"{out_dir}", msg
    else:
        # Return archive content in memory if no output directory specified
        return BytesIO(response.content), msg

request_archive_upload Link

request_archive_upload(host, scan_id, path, **kwargs)

Upload a scan archive file to a specified dataset on a server.

This function sends a POST request to upload a scan archive file to a particular dataset, utilizing the archive URL and optionally specified additional API-related request parameters. Ensures proper handling of file opening/closing procedures and response status checks.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

scan_id Link

str

The name of the target dataset for the archive upload.

required

path Link

(str, Path)

The local file system path to the archive to be uploaded.

required

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to PLANTDB_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

timeout int

A timeout, in seconds, to succeed the upload request. Defaults to 120.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
str

The time it took to upload the archive.

Raises:

Type Description
RequestException

If the HTTP request fails for any reason.

HTTPError

If the request returns an unsuccessful HTTP status code.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_archive_upload
>>> request_archive_upload('localhost', "arabidopsis000", path='/tmp/arabidopsis000.zip', port=5000)
'Upload completed in 0.10 seconds.'
Source code in plantdb/client/rest_api/requests.py
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
def request_archive_upload(host, scan_id, path, **kwargs):
    """Upload a scan archive file to a specified dataset on a server.

    This function sends a POST request to upload a scan archive file to a
    particular dataset, utilizing the archive URL and optionally specified
    additional API-related request parameters. Ensures proper handling of
    file opening/closing procedures and response status checks.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str
        The name of the target dataset for the archive upload.
    path : str, pathlib.Path
        The local file system path to the archive to be uploaded.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``PLANTDB_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    timeout : int, optional
        A timeout, in seconds, to succeed the upload request. Defaults to ``120``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    str
        The time it took to upload the archive.

    Raises
    ------
    requests.exceptions.RequestException
        If the HTTP request fails for any reason.
    requests.exceptions.HTTPError
        If the request returns an unsuccessful HTTP status code.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_archive_upload
    >>> request_archive_upload('localhost', "arabidopsis000", path='/tmp/arabidopsis000.zip', port=5000)
    'Upload completed in 0.10 seconds.'
    """
    import time
    from zipfile import ZipFile

    if isinstance(path, str):
        path = Path(path)
    # Verify path existence
    if not path.is_file():
        raise FileNotFoundError(f"The file at path '{path}' does not exist!")
    # Verify the integrity of the ZIP file
    try:
        with ZipFile(path, 'r') as zip_file:
            zip_file.testzip()
    except Exception as e:
        print(e)
        raise IOError(f"Invalid ZIP file '{path}!'")

    # Construct the URL for the archive upload:
    url = archive_url(host, scan_id, **kwargs)

    request_kwargs = {
        'session_token': kwargs.get('session_token', None),
        'timeout': kwargs.get('timeout', 120),
    }

    start_time = time.time()  # Start timing
    with open(path, "rb") as f:
        try:
            res = make_api_request(url,
                                   method="POST",
                                   files={"zip_file": (path.name, f, "application/zip")},
                                   stream=True,
                                   **request_kwargs)
        except requests.exceptions.Timeout:
            timeout = kwargs.get("timeout", 120)
            raise RuntimeError(f"The upload request timed out after {timeout} seconds.")
        except requests.exceptions.RequestException as e:
            raise RuntimeError(f"An error occurred during the upload: {e}")
    end_time = time.time()  # End timing

    if res.ok:
        duration = end_time - start_time
        return f"Upload completed in {duration:.2f} seconds."
    else:
        res.raise_for_status()  # Raise an error if the request failed

request_check_username Link

request_check_username(host, username, **kwargs)

Send a username availability request to the authentication service.

This helper function constructs a GET request to the login endpoint and forwards any additional keyword arguments to the URL generator function.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

username Link

str

The user identifier for authentication.

required

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
bool

A boolean flag indicating whether the username is valid (True) or not (False).

Notes
  • The password is transmitted as plain JSON in the request body; ensure the endpoint is served over HTTPS to protect credentials.
  • The function does not perform any client‑side validation of the credentials; errors are reported by the API response.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_check_username
>>> username_exists = request_check_username('localhost', 'admin', port=5000)
>>> print(username_exists)
True
Source code in plantdb/client/rest_api/requests.py
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
def request_check_username(host, username, **kwargs) -> bool:
    """Send a username availability request to the authentication service.

    This helper function constructs a GET request to the login endpoint
    and forwards any additional keyword arguments to the URL generator
    function.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    username : str
        The user identifier for authentication.

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.

    Returns
    -------
    bool
        A boolean flag indicating whether the username is valid (``True``) or not (``False``).

    Notes
    -----
    * The password is transmitted as plain JSON in the request body;
      ensure the endpoint is served over HTTPS to protect credentials.
    * The function does not perform any client‑side validation of the credentials;
      errors are reported by the API response.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_check_username
    >>> username_exists = request_check_username('localhost', 'admin', port=5000)
    >>> print(username_exists)
    True
    """
    url = login_url(host, **kwargs)
    return make_api_request(url, method="GET", params={'username': username}).json()['exists']

request_dataset_file_upload Link

request_dataset_file_upload(host, scan_id, file_path, chunk_size=0, **kwargs)

Uploads a file to the server using the DatasetFile POST endpoint.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

scan_id Link

str

The unique identifier of the scan associated with the file upload.

required

file_path Link

str

The path to the file to be uploaded.

required

chunk_size Link

int

The size of chunks (in bytes) to read and send, by default 0 (no chunking).

0

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
dict

A dictionary containing the server's response.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_dataset_file_upload
>>> request_dataset_file_upload(host, 'arabidopsis000', '/path/to/local/file.txt')
Source code in plantdb/client/rest_api/requests.py
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
def request_dataset_file_upload(host, scan_id, file_path, chunk_size=0, **kwargs):
    """Uploads a file to the server using the DatasetFile POST endpoint.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str
        The unique identifier of the scan associated with the file upload.
    file_path : str
        The path to the file to be uploaded.
    chunk_size : int, optional
        The size of chunks (in bytes) to read and send, by default 0 (no chunking).

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    dict
        A dictionary containing the server's response.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_dataset_file_upload
    >>> request_dataset_file_upload(host, 'arabidopsis000', '/path/to/local/file.txt')
    """
    from os.path import basename
    from os.path import getsize
    # Prepare the URL and headers
    url = origin_url(host, **kwargs)
    url = join_url(url, f"files/{scan_id}")

    filename = basename(file_path)
    file_size = getsize(file_path)
    # Create the request header
    headers = {
        "Content-Disposition": f"attachment; filename={filename}",
        "Content-Length": str(file_size),
        "X-File-Path": filename,
    }

    try:
        # Open the file for reading
        with open(file_path, 'rb') as f:
            if chunk_size > 0:
                # Upload in chunks
                headers["X-Chunk-Size"] = str(chunk_size)
                bytes_sent = 0
                while bytes_sent < file_size:
                    chunk = f.read(chunk_size)
                    response = make_api_request(
                        url,
                        method="POST",
                        headers=headers,
                        data=chunk,
                        session_token=kwargs.get('session_token', None)
                    )
                    bytes_sent += len(chunk)
                    # Check if the request was successful
                    if response.status_code not in (200, 201):
                        return {"error": "File upload failed", "status_code": response.status_code,
                                "response": response.json()}
            else:
                # Upload the entire file
                response = make_api_request(url, method='POST', headers=headers, data=f,
                                            session_token=kwargs.get('session_token', None))

        # Return the server's response
        if response.status_code in (200, 201):
            return response.json()
        else:
            return {"error": "File upload failed", "status_code": response.status_code, "response": response.json()}
    except Exception as e:
        return {"error": str(e)}

request_login Link

request_login(host, username, password, **kwargs)

Send a login request to the authentication service.

This helper function constructs a POST request to the login endpoint and forwards any additional keyword arguments to the URL generator function.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

username Link

str

The user identifier for authentication.

required

password Link

str

The user's secret password. It is sent in the request body and should be handled securely (e.g., over HTTPS).

required

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
dict

The login data from the response if successful.

Notes
  • The password is transmitted as plain JSON in the request body; ensure the endpoint is served over HTTPS to protect credentials.
  • The function does not perform any client‑side validation of the credentials; errors are reported by the API response.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_login
>>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
>>> print(list(login_data))
['access_token', 'message', 'refresh_token', 'user']
Source code in plantdb/client/rest_api/requests.py
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
def request_login(host, username, password, **kwargs) -> dict:
    """Send a login request to the authentication service.

    This helper function constructs a POST request to the login endpoint
    and forwards any additional keyword arguments to the URL generator
    function.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    username : str
        The user identifier for authentication.
    password : str
        The user's secret password. It is sent in the request body and
        should be handled securely (_e.g._, over HTTPS).

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.

    Returns
    -------
    dict
        The login data from the response if successful.

    Notes
    -----
    * The password is transmitted as plain JSON in the request body;
      ensure the endpoint is served over HTTPS to protect credentials.
    * The function does not perform any client‑side validation of the credentials;
      errors are reported by the API response.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_login
    >>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
    >>> print(list(login_data))
    ['access_token', 'message', 'refresh_token', 'user']
    """
    url = login_url(host, **kwargs)
    data = {
        'username': username,
        'password': password
    }
    return make_api_request(url, method="POST", json_data=data).json()

request_logout Link

request_logout(host, **kwargs)

Send a logout request to the authentication service.

This helper function constructs a POST request to the logout endpoint and forwards any additional keyword arguments to the URL generator function.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
tuple[bool, str]

A boolean flag indicating whether the logout request was successful (True) or not (False). A string with the log out message.

Notes
  • The session_token is transmitted as plain JSON in the request header; ensure the endpoint is served over HTTPS to protect credentials.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_login
>>> from plantdb.client.rest_api.requests import request_logout
>>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
>>> success, msg = request_logout('localhost', port=5000, session_token=login_data['access_token'])
>>> print(success)
True
Source code in plantdb/client/rest_api/requests.py
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
def request_logout(host, **kwargs) -> tuple[bool, str]:
    """Send a logout request to the authentication service.

    This helper function constructs a POST request to the logout endpoint
    and forwards any additional keyword arguments to the URL generator
    function.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    tuple[bool, str]
        A boolean flag indicating whether the logout request was successful (``True``) or not (``False``).
        A string with the log out message.

    Notes
    -----
    * The session_token is transmitted as plain JSON in the request header;
      ensure the endpoint is served over HTTPS to protect credentials.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_login
    >>> from plantdb.client.rest_api.requests import request_logout
    >>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
    >>> success, msg = request_logout('localhost', port=5000, session_token=login_data['access_token'])
    >>> print(success)
    True
    """
    url = logout_url(host, **kwargs)
    response = make_api_request(url, method="POST", session_token=kwargs.get('session_token', None))
    return response.ok, response.json()['message']

request_new_user Link

request_new_user(host, username, password, fullname, **kwargs)

Send a registration request to the authentication service.

This helper function constructs a POST request to the register endpoint and forwards any additional keyword arguments to the URL generator function.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

username Link

str

The user identifier to add.

required

password Link

str

The user's secret password to use. It is sent in the request body and should be handled securely (e.g., over HTTPS).

required

fullname Link

str

The user's full name to use.

required

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
bool

A boolean indicating whether the request was successful (True) or not (False).

Notes
  • The session_token is transmitted as plain JSON in the request header; ensure the endpoint is served over HTTPS to protect credentials.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_login
>>> from plantdb.client.rest_api.requests import request_logout
>>> from plantdb.client.rest_api.requests import request_new_user
>>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
>>> user_added = request_new_user('localhost', 'testuser', 'fake_password', 'Test User', port=5000, session_token=login_data['access_token'])
>>> print(user_added)
True
>>> logout = request_logout('localhost', port=5000, session_token=login_data['access_token'])
>>> login_data = request_login('localhost', 'testuser', 'fake_password', port=5000)
>>> print(login_data['user']['username'])
testuser
Source code in plantdb/client/rest_api/requests.py
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
def request_new_user(host, username, password, fullname, **kwargs) -> bool:
    """Send a registration request to the authentication service.

    This helper function constructs a POST request to the register endpoint
    and forwards any additional keyword arguments to the URL generator
    function.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    username : str
        The user identifier to add.
    password : str
        The user's secret password to use. It is sent in the request body and
        should be handled securely (e.g., over HTTPS).
    fullname : str
        The user's full name to use.

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    bool
        A boolean indicating whether the request was successful (``True``) or not (``False``).

    Notes
    -----
    * The session_token is transmitted as plain JSON in the request header;
      ensure the endpoint is served over HTTPS to protect credentials.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_login
    >>> from plantdb.client.rest_api.requests import request_logout
    >>> from plantdb.client.rest_api.requests import request_new_user
    >>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
    >>> user_added = request_new_user('localhost', 'testuser', 'fake_password', 'Test User', port=5000, session_token=login_data['access_token'])
    >>> print(user_added)
    True
    >>> logout = request_logout('localhost', port=5000, session_token=login_data['access_token'])
    >>> login_data = request_login('localhost', 'testuser', 'fake_password', port=5000)
    >>> print(login_data['user']['username'])
    testuser
    """
    url = register_url(host, **kwargs)
    data = {'username': username, 'fullname': fullname, 'password': password}
    return make_api_request(url, method="POST", json_data=data, session_token=kwargs.get('session_token', None)).ok

request_refresh Link

request_refresh(host, scan_id=None, **kwargs)

Refreshes the database, potentialy only for a specified dataset.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

scan_id Link

str or None

The name of the dataset to trigger a refresh. If None, the entire database is refreshed.

None

Other Parameters:

Name Type Description
port int or str

The port number of the PlantDB REST API server. Defaults to PLANTDB_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

timeout int

A timeout, in seconds, to succeed the refresh request. Defaults to 5.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
tuple[bool, str]

A boolean indicating whether the refresh request succeeded.

Raises:

Type Description
HTTPError

If the request fails or the response status is not successful.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_refresh
>>> success, message = request_refresh('localhost', "arabidopsis000", port = 5000)
>>> print(message)
Successfully reloaded scan 'arabidopsis000'
Source code in plantdb/client/rest_api/requests.py
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
def request_refresh(host, scan_id=None, **kwargs) -> tuple[bool, str]:
    """Refreshes the database, potentialy only for a specified dataset.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str or None
        The name of the dataset to trigger a refresh.
        If ``None``, the entire database is refreshed.

    Other Parameters
    ----------------
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``PLANTDB_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    timeout : int, optional
        A timeout, in seconds, to succeed the refresh request. Defaults to ``5``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    tuple[bool, str]
        A boolean indicating whether the refresh request succeeded.

    Raises
    ------
    HTTPError
        If the request fails or the response status is not successful.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_refresh
    >>> success, message = request_refresh('localhost', "arabidopsis000", port = 5000)
    >>> print(message)
    Successfully reloaded scan 'arabidopsis000'
    """
    url = refresh_url(host, scan_id, **kwargs)
    response = make_api_request(url, session_token=kwargs.get('session_token', None))
    return response.ok, response.json()["message"]

request_scan_data Link

request_scan_data(host, scan_id, **kwargs)

Retrieve the data dictionary for a given scan dataset from the PlantDB REST API.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

scan_id Link

str

The name of the scan dataset to be retrieved.

required

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
dict

The data dictionary for the given scan dataset obtained from the response, if successful.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_scan_data
>>> from plantdb.client.rest_api.requests import request_login
>>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
>>> scan_data = request_scan_data('localhost', 'real_plant', port=5000, session_token=login_data['access_token'])
>>> print(scan_data['id'])
real_plant
>>> print(scan_data['hasColmap'])
False
Source code in plantdb/client/rest_api/requests.py
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
def request_scan_data(host, scan_id, **kwargs) -> dict:
    """Retrieve the data dictionary for a given scan dataset from the PlantDB REST API.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str
        The name of the scan dataset to be retrieved.

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    dict
        The data dictionary for the given scan dataset obtained from the response, if successful.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_scan_data
    >>> from plantdb.client.rest_api.requests import request_login
    >>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
    >>> scan_data = request_scan_data('localhost', 'real_plant', port=5000, session_token=login_data['access_token'])
    >>> print(scan_data['id'])
    real_plant
    >>> print(scan_data['hasColmap'])
    False
    """
    scan_id = sanitize_name(scan_id)
    url = scan_url(host, scan_id, **kwargs)
    response = make_api_request(url=url, session_token=kwargs.get('session_token', None))
    if response.ok:
        return response.json()
    elif response.status_code == 404:
        print(response.json()['message'])
        return {}
    else:
        print(response.json()['message'])
        return {}

request_scan_image Link

request_scan_image(host, scan_id, fileset_id, file_id, size='orig', as_base64=False, **kwargs)

Get the image for a scan dataset and task fileset served by the PlantDB REST API.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

scan_id Link

str

The name of the scan dataset to be retrieved.

required

fileset_id Link

str

The name of the fileset containing the image to be retrieved.

required

file_id Link

str

The name of the image file to be retrieved.

required

size Link

(orig, large, thumb)

If an integer, use it as the size of the cached image to create and return. Else, should be a string, defaulting to 'orig', and it works as follows: * 'thumb': image max width and height to 150. * 'large': image max width and height to 1500; * 'orig': original image, no cache;

'orig'

as_base64 Link

bool

A boolean flag indicating whether to return an image as a base64 string.

False

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
tuple[str, str, Union[str, bytes]]

If as_base64==True, a dictionary with the 'image' encoded as base64 and the mimetype in 'content-type'. Else the image data as bytes.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_scan_image
>>> import pybase64
>>> from PIL import Image
>>> from io import BytesIO
>>> # Example #1 - Get an image as binary data:
>>> db_img = ['real_plant', 'images', '00000_rgb']
>>> _, _, img_bytes = request_scan_image('localhost', *db_img, port=5000)  # download the image
>>> print(img_bytes[:10])
b'ÿØÿàJFIF'
>>> image = Image.open(BytesIO(img_bytes))  # Open the image from the bytes data
>>> image.show()  # Display the image
>>> # Example #2 - Get an image as base64 data:
>>> _, _, b64_string = request_scan_image('localhost', *db_img, port=5000, as_base64=True)
>>> print(b64_string[:50])
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUEBAQEAwUEBAQGBQ
>>> image_data = pybase64.b64decode(b64_string)
>>> image = Image.open(BytesIO(image_data))  # Open the image from the base64 data
>>> image.show()
Source code in plantdb/client/rest_api/requests.py
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
def request_scan_image(host, scan_id, fileset_id, file_id,
                       size='orig', as_base64=False, **kwargs) -> tuple[str, str, Union[str, bytes]]:
    """Get the image for a scan dataset and task fileset served by the PlantDB REST API.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str
        The name of the scan dataset to be retrieved.
    fileset_id : str
        The name of the fileset containing the image to be retrieved.
    file_id : str
        The name of the image file to be retrieved.
    size : {'orig', 'large', 'thumb'} or int, optional
        If an integer, use  it as the size of the cached image to create and return.
        Else, should be a string, defaulting to ``'orig'``, and it works as follows:
           * ``'thumb'``: image max width and height to `150`.
           * ``'large'``: image max width and height to `1500`;
           * ``'orig'``: original image, no cache;
    as_base64 : bool
        A boolean flag indicating whether to return an image as a base64 string.

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    tuple[str, str, Union[str, bytes]]
        If ``as_base64==True``, a dictionary with the 'image' encoded as base64 and the mimetype in 'content-type'.
        Else the image data as bytes.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_scan_image
    >>> import pybase64
    >>> from PIL import Image
    >>> from io import BytesIO
    >>> # Example #1 - Get an image as binary data:
    >>> db_img = ['real_plant', 'images', '00000_rgb']
    >>> _, _, img_bytes = request_scan_image('localhost', *db_img, port=5000)  # download the image
    >>> print(img_bytes[:10])
    b'\xff\xd8\xff\xe0\x00\x10JFIF'
    >>> image = Image.open(BytesIO(img_bytes))  # Open the image from the bytes data
    >>> image.show()  # Display the image
    >>> # Example #2 - Get an image as base64 data:
    >>> _, _, b64_string = request_scan_image('localhost', *db_img, port=5000, as_base64=True)
    >>> print(b64_string[:50])
    /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUEBAQEAwUEBAQGBQ
    >>> image_data = pybase64.b64decode(b64_string)
    >>> image = Image.open(BytesIO(image_data))  # Open the image from the base64 data
    >>> image.show()
    """
    url = scan_image_url(host, scan_id, fileset_id, file_id, size, as_base64, **kwargs)
    response = make_api_request(url=url, session_token=kwargs.get('session_token', None))
    content_type = response.headers.get('Content-Type')
    encoding = response.headers.get("X-Content-Encoding")
    if as_base64:
        content_type = response.json()['content-type']
        img_str = response.json()['image']
        return content_type, encoding, img_str
    else:
        return content_type, encoding, response.content

request_scan_names_list Link

request_scan_names_list(host, **kwargs)

Get the list of the scan datasets names served by the PlantDB REST API.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
list[str]

The list of the scan datasets names from the response, if successful.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_scan_names_list
>>> print(request_scan_names_list('localhost', port=5000)
['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
Source code in plantdb/client/rest_api/requests.py
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
def request_scan_names_list(host, **kwargs) -> list[str]:
    """Get the list of the scan datasets names served by the PlantDB REST API.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    list[str]
        The list of the scan datasets names from the response, if successful.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_scan_names_list
    >>> print(request_scan_names_list('localhost', port=5000)
    ['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
    """
    url = scans_url(host, **kwargs)
    return make_api_request(url=url, method="GET", session_token=kwargs.get('session_token', None)).json()

request_scan_tasks_fileset Link

request_scan_tasks_fileset(host, scan_id, **kwargs)

Get the task name to fileset name mapping dictionary from the REST API.

Parameters:

Name Type Description Default

host Link

str

The hostname or IP address of the PlantDB REST API server.

required

scan_id Link

str

The name of the dataset to retrieve the mapping for.

required

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
dict

The mapping of the task name to fileset name.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_scan_tasks_fileset
>>> request_scan_tasks_fileset('localhost', 'real_plant', port=5000)
{'images': 'images'}
>>> request_scan_tasks_fileset('localhost', 'real_plant_analyzed', port=5000)
{'images': 'images',
 'AnglesAndInternodes': 'AnglesAndInternodes_1_0_2_0_6_0_6dd64fc595',
 'TreeGraph': 'TreeGraph__False_CurveSkeleton_c304a2cc71',
 'CurveSkeleton': 'CurveSkeleton__TriangleMesh_0393cb5708',
 'TriangleMesh': 'TriangleMesh_9_most_connected_t_open3d_00e095c359',
 'PointCloud': 'PointCloud_1_0_1_0_10_0_7ee836e5a9',
 'Voxels': 'Voxels___x____300__450__colmap_camera_False_2a093f0ccc',
 'Masks': 'Masks_1__0__1__0____channel____rgb_5619aa428d',
 'Colmap': 'Colmap_True_null_SIMPLE_RADIAL_ffcef49fdc',
 'Undistorted': 'Undistorted_SIMPLE_RADIAL_Colmap__a333f181b7'}
Source code in plantdb/client/rest_api/requests.py
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
def request_scan_tasks_fileset(host, scan_id, **kwargs) -> dict:
    """Get the task name to fileset name mapping dictionary from the REST API.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str
        The name of the dataset to retrieve the mapping for.

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    dict
        The mapping of the task name to fileset name.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_scan_tasks_fileset
    >>> request_scan_tasks_fileset('localhost', 'real_plant', port=5000)
    {'images': 'images'}
    >>> request_scan_tasks_fileset('localhost', 'real_plant_analyzed', port=5000)
    {'images': 'images',
     'AnglesAndInternodes': 'AnglesAndInternodes_1_0_2_0_6_0_6dd64fc595',
     'TreeGraph': 'TreeGraph__False_CurveSkeleton_c304a2cc71',
     'CurveSkeleton': 'CurveSkeleton__TriangleMesh_0393cb5708',
     'TriangleMesh': 'TriangleMesh_9_most_connected_t_open3d_00e095c359',
     'PointCloud': 'PointCloud_1_0_1_0_10_0_7ee836e5a9',
     'Voxels': 'Voxels___x____300__450__colmap_camera_False_2a093f0ccc',
     'Masks': 'Masks_1__0__1__0____channel____rgb_5619aa428d',
     'Colmap': 'Colmap_True_null_SIMPLE_RADIAL_ffcef49fdc',
     'Undistorted': 'Undistorted_SIMPLE_RADIAL_Colmap__a333f181b7'}
     """
    return request_scan_data(host, scan_id, **kwargs).get('tasks_fileset', dict())

request_scans_info Link

request_scans_info(host, **kwargs)

Retrieve the information dictionary for all scans from the PlantDB REST API.

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
list[dict]

The list of scan information dictionaries obtained from the response, if successful.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_scans_info
>>> from plantdb.client.rest_api.requests import request_login
>>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
>>> scans_info = request_scans_info('localhost', port=5000, session_token=login_data['access_token'])
>>> print(sorted([scan['id'] for scan in scans_info]))
['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
Source code in plantdb/client/rest_api/requests.py
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
def request_scans_info(host, **kwargs) -> list[dict]:
    """Retrieve the information dictionary for all scans from the PlantDB REST API.

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    list[dict]
        The list of scan information dictionaries obtained from the response, if successful.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_scans_info
    >>> from plantdb.client.rest_api.requests import request_login
    >>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
    >>> scans_info = request_scans_info('localhost', port=5000, session_token=login_data['access_token'])
    >>> print(sorted([scan['id'] for scan in scans_info]))
    ['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
    """
    scan_list = request_scan_names_list(host, **kwargs)
    return [make_api_request(url=scan_url(host, scan, **kwargs), session_token=kwargs.get('session_token', None)).json()
            for scan in scan_list]

request_token_refresh Link

request_token_refresh(host, **kwargs)

Refresh a token by making a POST request to the token refresh endpoint.

Parameters:

Name Type Description Default

host Link

str

The hostname or base URL used to construct the refresh endpoint.

required

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
dict

The token refresh data from the response, if successful.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_login
>>> from plantdb.client.rest_api.requests import request_token_refresh
>>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
>>> token_refresh = request_token_refresh('localhost', port=5000, refresh_token=login_data['refresh_token'])
>>> print([key for key in token_refresh.json() if 'token' in key])
['access_token', 'refresh_token']
Source code in plantdb/client/rest_api/requests.py
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
def request_token_refresh(host, **kwargs) -> dict:
    """Refresh a token by making a POST request to the token refresh endpoint.

    Parameters
    ----------
    host : str
        The hostname or base URL used to construct the refresh endpoint.

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    dict
        The token refresh data from the response, if successful.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_login
    >>> from plantdb.client.rest_api.requests import request_token_refresh
    >>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
    >>> token_refresh = request_token_refresh('localhost', port=5000, refresh_token=login_data['refresh_token'])
    >>> print([key for key in token_refresh.json() if 'token' in key])
    ['access_token', 'refresh_token']
    """
    url = token_refresh_url(host, **kwargs)
    return make_api_request(url, method="POST", json_data={'refresh_token': kwargs.get('refresh_token', None)}).json()

request_token_validation Link

request_token_validation(host, **kwargs)

Validate a token by making a POST request to the token validation endpoint.

Parameters:

Name Type Description Default

host Link

str

The hostname or base URL used to construct the validation endpoint.

required

Other Parameters:

Name Type Description
port int

The PlantDB API port number, defaults to None.

prefix str

A path prefix for the PlantDB API, defaults to None.

ssl bool

A boolean flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

session_token str

The PlantDB REST API session token of the user.

Returns:

Type Description
dict

The token validation data from the response, if successful.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api.requests import request_login
>>> from plantdb.client.rest_api.requests import request_token_validation
>>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
>>> token_data = request_token_validation('localhost', port=5000, session_token=login_data['access_token'])
>>> print(token_data['user'])
{'username': 'admin', 'fullname': 'PlantDB Admin'}
Source code in plantdb/client/rest_api/requests.py
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
def request_token_validation(host, **kwargs) -> dict:
    """Validate a token by making a POST request to the token validation endpoint.

    Parameters
    ----------
    host : str
        The hostname or base URL used to construct the validation endpoint.

    Other Parameters
    ----------------
    port : int
        The PlantDB API port number, defaults to ``None``.
    prefix : str
        A path prefix for the PlantDB API, defaults to ``None``.
    ssl : bool
        A boolean flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.
    session_token : str
        The PlantDB REST API session token of the user.

    Returns
    -------
    dict
        The token validation data from the response, if successful.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api.requests import request_login
    >>> from plantdb.client.rest_api.requests import request_token_validation
    >>> login_data = request_login('localhost', 'admin', 'admin', port=5000)
    >>> token_data = request_token_validation('localhost', port=5000, session_token=login_data['access_token'])
    >>> print(token_data['user'])
    {'username': 'admin', 'fullname': 'PlantDB Admin'}
    """
    url = token_validation_url(host, **kwargs)
    return make_api_request(url, method="POST", session_token=kwargs.get('session_token', None)).json()