Skip to content

rest_api

REST API Client ModuleLink

A Python module that provides a comprehensive interface for interacting with a scanning and image processing REST API service. This client handles various operations related to scan management, image processing, and data retrieval while abstracting away the complexities of HTTP communications.

Key FeaturesLink

  • Scan Management: Create, retrieve, refresh, and archive scans
  • Image Processing: Handle scan images, preview generations, and image data retrieval
  • Configuration Management: Load and manage scan and reconstruction configurations
  • Data Parsing: Support for multiple data formats including PCD, mesh, skeleton, and JSON
  • File Operations: Upload and download capabilities for datasets and scan archives
  • Security: Built-in certificate handling for secure API communications
  • Task Management: Retrieve and process task-related data and file sets
  • URL Generation: Automated URL construction for various API endpoints

Environment variablesLink

  • PLANTDB_HOST: default hostname to PlantDB REST API
  • PLANTDB_PORT: default port to PlantDB REST API
  • PLANTDB_PREFIX: default URL prefix for the plantdb REST API
  • CERT_PATH: Path to a certificate file for SSL verification. If None (default), default SSL verification is used.

api_token_url Link

api_token_url(host, **kwargs)

Generate the full URL for the PlantDB API token endpoint.

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.

Returns:

Type Description
str

The fully qualified URL as a string.

Examples:

>>> from plantdb.client.rest_api import api_token_url
>>> # Basic usage with default configuration
>>> url = api_token_url('localhost')
>>> print(url)
http://localhost/create-api-token
Source code in plantdb/client/rest_api.py
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
def api_token_url(host, **kwargs):
    """Generate the full URL for the PlantDB API token endpoint.

    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``.

    Returns
    -------
    str
        The fully qualified URL as a string.

    Examples
    --------
    >>> from plantdb.client.rest_api import api_token_url
    >>> # Basic usage with default configuration
    >>> url = api_token_url('localhost')
    >>> print(url)
    http://localhost/create-api-token
    """
    url = origin_url(host, **kwargs)
    return join_url(url, api_endpoints.create_api_token())

archive_url Link

archive_url(host, scan_id, **kwargs)

Generates a formatted URL for accessing the archive of a specific 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

Name of the dataset to access in the archive.

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
str

Fully constructed URL for accessing the specified dataset archive.

Examples:

>>> from plantdb.client.rest_api import archive_url
>>> archive_url('localhost', 'arabidopsis000')
'http://localhost/archive/arabidopsis000'
>>> archive_url('localhost', '../arabidopsis000')
'http://localhost/archive/arabidopsis000'
>>> archive_url('localhost', 'arabidopsis+000')
ValueError: Invalid dataset name: 'arabidopsis+000'. Dataset names must be alphanumeric and can include underscores or dashes.
>>> archive_url('localhost', 'arabidopsis000', prefix='/plantdb')
'http://localhost/plantdb/archive/arabidopsis000'
Source code in plantdb/client/rest_api.py
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
def archive_url(host, scan_id, **kwargs):
    """Generates a formatted URL for accessing the archive of a specific dataset.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str
        Name of the dataset to access in the archive.

    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
    -------
    str
        Fully constructed URL for accessing the specified dataset archive.

    Examples
    --------
    >>> from plantdb.client.rest_api import archive_url
    >>> archive_url('localhost', 'arabidopsis000')
    'http://localhost/archive/arabidopsis000'
    >>> archive_url('localhost', '../arabidopsis000')
    'http://localhost/archive/arabidopsis000'
    >>> archive_url('localhost', 'arabidopsis+000')
    ValueError: Invalid dataset name: 'arabidopsis+000'. Dataset names must be alphanumeric and can include underscores or dashes.
    >>> archive_url('localhost', 'arabidopsis000', prefix='/plantdb')
    'http://localhost/plantdb/archive/arabidopsis000'
    """
    url = origin_url(host, **kwargs)
    return join_url(url, api_endpoints.archive(scan_id, **kwargs))

get_angles_and_internodes_data Link

get_angles_and_internodes_data(host, scan_id, **kwargs)

Return a dictionary with 'angles' and 'internodes' data for selected dataset, if it exists.

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.

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

A dictionary with 'angles' and 'internodes' data.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_angles_and_internodes_data
>>> data = get_angles_and_internodes_data('real_plant_analyzed')
>>> print(list(data.keys()))
['angles', 'internodes']
>>> print(len(data['angles']))
33
Source code in plantdb/client/rest_api.py
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
def get_angles_and_internodes_data(host, scan_id, **kwargs):
    """Return a dictionary with 'angles' and 'internodes' data for selected dataset, if it exists.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str
        The name of the 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``.

    Returns
    -------
    dict
        A dictionary with 'angles' and 'internodes' data.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_angles_and_internodes_data
    >>> data = get_angles_and_internodes_data('real_plant_analyzed')
    >>> print(list(data.keys()))
    ['angles', 'internodes']
    >>> print(len(data['angles']))
    33
    """
    url = origin_url(host, **kwargs)

    response = make_api_request(join_url(url, f"sequence/{scan_id}"),
                                session_token=kwargs.get('session_token', None))
    if response.ok:
        data = json.loads(response.content.decode('utf-8'))
        return {seq: data[seq] for seq in ['angles', 'internodes']}
    else:
        return None

get_reconstruction_config Link

get_reconstruction_config(host, scan_id, cfg_fname='pipeline.toml', **kwargs)

Return the reconstruction configuration for selected dataset, if it exists.

Parameters:

Name Type Description Default

scan_id Link

str

The name of the dataset.

required

cfg_fname Link

str

The name of the configuration file.

'pipeline.toml'

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 configuration dictionary.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_reconstruction_config
>>> cfg = get_reconstruction_config('real_plant_analyzed')
>>> cfg['PointCloud']['upstream_task']
'Voxels'
Source code in plantdb/client/rest_api.py
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
def get_reconstruction_config(host, scan_id, cfg_fname='pipeline.toml', **kwargs):
    """Return the reconstruction configuration for selected dataset, if it exists.

    Parameters
    ----------
    scan_id : str
        The name of the dataset.
    cfg_fname : str, optional
        The name of the configuration file.

    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 configuration dictionary.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_reconstruction_config
    >>> cfg = get_reconstruction_config('real_plant_analyzed')
    >>> cfg['PointCloud']['upstream_task']
    'Voxels'

    """
    return get_toml_file(host, scan_id, cfg_fname, **kwargs)

get_scan_config Link

get_scan_config(host, scan_id, cfg_fname='scan.toml', **kwargs)

Return the scan configuration for selected dataset, if it exists.

Parameters:

Name Type Description Default

scan_id Link

str

The name of the dataset.

required

cfg_fname Link

str

The name of the configuration file.

'scan.toml'

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 configuration dictionary.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_scan_config
>>> cfg = get_scan_config('real_plant')
>>> cfg['ScanPath']['class_name']
'Circle'
Source code in plantdb/client/rest_api.py
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
def get_scan_config(host, scan_id, cfg_fname='scan.toml', **kwargs):
    """Return the scan configuration for selected dataset, if it exists.

    Parameters
    ----------
    scan_id : str
        The name of the dataset.
    cfg_fname : str, optional
        The name of the configuration file.

    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 configuration dictionary.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_scan_config
    >>> cfg = get_scan_config('real_plant')
    >>> cfg['ScanPath']['class_name']
    'Circle'

    """
    return get_toml_file(host, scan_id, cfg_fname, **kwargs)

get_task_data Link

get_task_data(host, scan_id, task, filename=None, api_data=None, **kwargs)

Get the data corresponding to a dataset/task/filename.

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.

required

task Link

str

The name of the task.

required

filename Link

str

The name of the file to load. If not specified defaults to the main file returned by the task as defined in filesUri_task_mapping.

None

api_data Link

dict

The dictionary of information for the dataset as returned by the REST API. If not specified, fetch it from the REST API.

None

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
any

The parsed data.

See Also

plantdb.client.rest_api.parse_task_requests_data

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> import numpy as np
>>> from plantdb.client.rest_api import get_task_data
>>> pcd = get_task_data('real_plant_analyzed', 'PointCloud')
>>> np.array(pcd).shape
(3, 57890)
Source code in plantdb/client/rest_api.py
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
def get_task_data(host, scan_id, task, filename=None, api_data=None, **kwargs):
    """Get the data corresponding to a `dataset/task/filename`.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str
        The name of the dataset.
    task : str
        The name of the task.
    filename : str, optional
        The name of the file to load.
        If not specified defaults to the main file returned by the task as defined in `filesUri_task_mapping`.
    api_data : dict, optional
        The dictionary of information for the dataset as returned by the REST API.
        If not specified, fetch it from the 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``.

    Returns
    -------
    any
        The parsed data.

    See Also
    --------
    plantdb.client.rest_api.parse_task_requests_data

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> import numpy as np
    >>> from plantdb.client.rest_api import get_task_data
    >>> pcd = get_task_data('real_plant_analyzed', 'PointCloud')
    >>> np.array(pcd).shape
    (3, 57890)
    """
    if api_data is None:
        api_data = request_scan_data(host, scan_id, **kwargs)
    # Get data from `File` resource of REST API:
    ext = None
    if filename is None:
        file_uri = api_data["filesUri"][task_filesUri_mapping[task]]
    else:
        _, ext = Path(filename).suffix.split('.')
        file_uri = api_endpoints.file(scan_id, api_data["tasks_fileset"][task], filename)

    url = origin_url(host, **kwargs)

    data = make_api_request(url + file_uri, session_token=kwargs.get('session_token', None)).content
    return parse_task_requests_data(task, data, ext)

get_toml_file Link

get_toml_file(host, scan_id, file_path, **kwargs)

Return a loaded TOML file for selected dataset, if it exists.

Parameters:

Name Type Description Default

scan_id Link

str

The name of the dataset.

required

file_path Link

str

The path to the TOML file.

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 configuration dictionary.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_toml_file
>>> cfg = get_toml_file('real_plant_analyzed', 'pipeline.toml')
>>> cfg['PointCloud']
{'upstream_task': 'Voxels', 'level_set_value': 1.0}
Source code in plantdb/client/rest_api.py
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
def get_toml_file(host, scan_id, file_path, **kwargs):
    """Return a loaded TOML file for selected dataset, if it exists.

    Parameters
    ----------
    scan_id : str
        The name of the dataset.
    file_path : str
        The path to the TOML file.

    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 configuration dictionary.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_toml_file
    >>> cfg = get_toml_file('real_plant_analyzed', 'pipeline.toml')
    >>> cfg['PointCloud']
    {'upstream_task': 'Voxels', 'level_set_value': 1.0}
    """
    url = scan_file_url(host, scan_id, file_path, **kwargs)
    return _load_toml_from_url(url, **kwargs)

list_task_images_uri Link

list_task_images_uri(host, scan_id, task_name='images', size='orig', as_base64=True, **kwargs)

Get the list of images URI for a given dataset and task name.

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 images for.

required

task_name Link

str

The name of the task to retrieve the images from. Defaults to 'images'.

'images'

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.

True

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
list of str

The list of image URI strings for the PlantDB REST API.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import list_task_images_uri
>>> print(list_task_images_uri('localhost', 'real_plant')[2])
http://localhost/image/real_plant/images/00002_rgb?size=orig
>>> print(list_task_images_uri('localhost', 'real_plant', size=100)[2])
http://localhost/image/real_plant/images/00002_rgb?size=100
Source code in plantdb/client/rest_api.py
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
def list_task_images_uri(host, scan_id, task_name='images', size='orig', as_base64=True, **kwargs):
    """Get the list of images URI for a given dataset and task name.

    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 images for.
    task_name : str, optional
        The name of the task to retrieve the images from. Defaults to 'images'.
    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``.

    Returns
    -------
    list of str
        The list of image URI strings for the PlantDB REST API.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import list_task_images_uri
    >>> print(list_task_images_uri('localhost', 'real_plant')[2])
    http://localhost/image/real_plant/images/00002_rgb?size=orig
    >>> print(list_task_images_uri('localhost', 'real_plant', size=100)[2])
    http://localhost/image/real_plant/images/00002_rgb?size=100
    """
    scan_info = request_scan_data(host, scan_id, **kwargs)
    tasks_id = scan_info["tasks_fileset"][task_name]
    images = scan_info["images"]
    url = origin_url(host, **kwargs)
    return [join_url(url, api_endpoints.image(scan_id, tasks_id, Path(img).stem, size, as_base64, **kwargs))
        for img in images]

login_url Link

login_url(host, **kwargs)

Generate the full URL for the PlantDB API login endpoint.

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.

Returns:

Type Description
str

The fully qualified login URL as a string.

Examples:

>>> from plantdb.client.rest_api import login_url
>>> # Default URL using module level constants
>>> url = login_url('localhost')
>>> print(url)
http://localhost/login
>>> # Override host, add a prefix and enable SSL
>>> url = login_url('dev.romi.local', prefix="/plantdb", ssl=True)
>>> print(url)
https://dev.romi.local/plantdb/login
Source code in plantdb/client/rest_api.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def login_url(host, **kwargs):
    """Generate the full URL for the PlantDB API login endpoint.

    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``.

    Returns
    -------
    str
        The fully qualified login URL as a string.

    Examples
    --------
    >>> from plantdb.client.rest_api import login_url
    >>> # Default URL using module level constants
    >>> url = login_url('localhost')
    >>> print(url)
    http://localhost/login
    >>> # Override host, add a prefix and enable SSL
    >>> url = login_url('dev.romi.local', prefix="/plantdb", ssl=True)
    >>> print(url)
    https://dev.romi.local/plantdb/login
    """
    origin = origin_url(host, **kwargs)
    return join_url(origin, api_endpoints.login(**kwargs))

logout_url Link

logout_url(host, **kwargs)

Generate the full URL for the PlantDB API logoutn endpoint.

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.

Returns:

Type Description
str

The fully qualified logoutn URL as a string.

Examples:

>>> from plantdb.client.rest_api import logout_url
>>> # Basic usage with default configuration
>>> url = logout_url('localhost')
>>> print(url)
http://localhost/logout
>>> # Specify a custom prefix and enable SSL
>>> url = logout_url('dev.romi.local', prefix="/plantdb", ssl=True)
>>> print(url)
https://dev.romi.local/plantdb/logout
Source code in plantdb/client/rest_api.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def logout_url(host, **kwargs):
    """Generate the full URL for the PlantDB API logoutn endpoint.

    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``.

    Returns
    -------
    str
        The fully qualified logoutn URL as a string.

    Examples
    --------
    >>> from plantdb.client.rest_api import logout_url
    >>> # Basic usage with default configuration
    >>> url = logout_url('localhost')
    >>> print(url)
    http://localhost/logout
    >>> # Specify a custom prefix and enable SSL
    >>> url = logout_url('dev.romi.local', prefix="/plantdb", ssl=True)
    >>> print(url)
    https://dev.romi.local/plantdb/logout
    """
    url = origin_url(host, **kwargs)
    return join_url(url, api_endpoints.logout(**kwargs))

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 import make_api_request
>>> from plantdb.client.rest_api 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.py
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
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 import make_api_request
    >>> from plantdb.client.rest_api 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

origin_url Link

origin_url(host, port=None, ssl=False, **kwargs)

Construct a URL string from host, optional port, and SSL flag.

Parameters:

Name Type Description Default

host Link

str

Hostname or URL. May optionally include a scheme (e.g., http:// or https://). If a scheme is present and contains the character s, the function treats it as HTTPS and forces ssl to True.

required

port Link

int or str

Port number to append to the host. If an int is supplied, it is converted to a string; a leading colon is stripped before it is added. The default is None which results in no port being added.

None

ssl Link

bool

When True the URL will use the https scheme. The value is overridden to True if the supplied host already contains a scheme with an s character.

False

Returns:

Type Description
url

The fully‑qualified URL string constructed from the supplied parts.

Raises:

Type Description
TypeError

If host is not a string or does not support split (e.g., None).

Notes

The function does not validate that the resulting URL points to a reachable endpoint; it only assembles the string. Supplying both a scheme in host and ssl=True will result in the scheme dictated by the original host (HTTPS if the original scheme contains s).

Examples:

>>> from plantdb.client.rest_api import origin_url
>>> origin_url('example.com')
'http://example.com'
>>> origin_url('example.com', 8080)
'http://example.com:8080'
>>> origin_url('https://example.com')
'https://example.com'
>>> origin_url('https://example.com/api/v1')
'https://example.com'
>>> origin_url('http://example.com', ssl=True)
'https://example.com'
>>> origin_url('example.com', port='443', ssl=True)
'https://example.com:443'
Source code in plantdb/client/rest_api.py
 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
def origin_url(host, port=None, ssl=False, **kwargs) -> str:
    """Construct a URL string from host, optional port, and SSL flag.

    Parameters
    ----------
    host : str
        Hostname or URL. May optionally include a scheme (e.g., ``http://`` or
        ``https://``). If a scheme is present and contains the character ``s``,
        the function treats it as HTTPS and forces ``ssl`` to ``True``.
    port : int or str, optional
        Port number to append to the host. If an ``int`` is supplied, it is
        converted to a string; a leading colon is stripped before it is added.
        The default is ``None`` which results in no port being added.
    ssl : bool, optional
        When ``True`` the URL will use the ``https`` scheme. The value is
        overridden to ``True`` if the supplied ``host`` already contains a scheme
        with an ``s`` character.

    Returns
    -------
    url
        The fully‑qualified URL string constructed from the supplied parts.

    Raises
    ------
    TypeError
        If ``host`` is not a string or does not support ``split`` (e.g., ``None``).

    Notes
    -----
    The function does **not** validate that the resulting URL points to a
    reachable endpoint; it only assembles the string. Supplying both a scheme
    in ``host`` and ``ssl=True`` will result in the scheme dictated by the
    original ``host`` (HTTPS if the original scheme contains ``s``).

    Examples
    --------
    >>> from plantdb.client.rest_api import origin_url
    >>> origin_url('example.com')
    'http://example.com'
    >>> origin_url('example.com', 8080)
    'http://example.com:8080'
    >>> origin_url('https://example.com')
    'https://example.com'
    >>> origin_url('https://example.com/api/v1')
    'https://example.com'
    >>> origin_url('http://example.com', ssl=True)
    'https://example.com'
    >>> origin_url('example.com', port='443', ssl=True)
    'https://example.com:443'
    """
    if not isinstance(host, str):
        raise TypeError("host must be a string")

    # Parse the incoming host value
    parsed = urlparse(host)

    # If no scheme was supplied, ``urlparse`` treats the whole string as a
    # path.  In that case we split the first “/” to obtain the netloc.
    if not parsed.scheme:
        # e.g. "example.com/api/v1" -> netloc="example.com", path="/api/v1"
        first_slash = parsed.path.find("/")
        if first_slash == -1:
            netloc, path = parsed.path, ""
        else:
            netloc = parsed.path[:first_slash]
            path = parsed.path[first_slash:]
        scheme = ""
    else:
        scheme = parsed.scheme
        netloc = parsed.netloc
        path = parsed.path

    # If the original string already contains a scheme that contains an “s” (i.e. https) it forces ``ssl=True``.
    if scheme and "s" in scheme.lower():
        ssl = True
    final_scheme = "https" if ssl else "http"

    # Apply an explicit ``port`` argument (overwrites any existing one)
    if port is not None:
        # ``splitport`` safely separates host from any existing port.
        hostname, _ = splitport(netloc)
        # Ensure ``port`` is a clean string without a leading colon.
        clean_port = str(port).lstrip(":")
        netloc = f"{hostname}:{clean_port}"

    # Re‑assemble the URL, excluding the original path (if any)
    return urlunparse((final_scheme, netloc, "", "", "", ""))

parse_requests_json Link

parse_requests_json(data)

Parse a requests content, should be from a AnglesAndInternodes task source.

Parameters:

Name Type Description Default

data Link

buffer

The data source from a requests content.

required

Returns:

Type Description
dict

The full angles and internodes dictionary with 'angles', 'internodes', '' & '' entries.

Source code in plantdb/client/rest_api.py
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
def parse_requests_json(data):
    """Parse a requests content, should be from a AnglesAndInternodes task source.

    Parameters
    ----------
    data : buffer
        The data source from a requests content.

    Returns
    -------
    dict
        The full angles and internodes dictionary with 'angles', 'internodes', '' & '' entries.
    """
    return json.loads(data)

parse_requests_mesh Link

parse_requests_mesh(data)

Parse a requests content, should be from a TriangleMesh task source.

Parameters:

Name Type Description Default

data Link

buffer

The data source from a requests content.

required

Returns:

Type Description
dict

The parsed triangular mesh with two entries: 'vertices' for vertex coordinates and 'triangles' for triangle coordinates.

Source code in plantdb/client/rest_api.py
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
def parse_requests_mesh(data):
    """Parse a requests content, should be from a TriangleMesh task source.

    Parameters
    ----------
    data : buffer
        The data source from a requests content.

    Returns
    -------
    dict
        The parsed triangular mesh with two entries: 'vertices' for vertex coordinates and 'triangles' for triangle coordinates.
    """
    ## Read the PLY as a `PlyData`:
    mesh_data = PlyData.read(BytesIO(data))
    ## Convert the `PlyData`:
    return {"vertices": _ply_vertex_to_array(mesh_data),
            "triangles": _ply_face_to_array(mesh_data)}

parse_requests_pcd Link

parse_requests_pcd(data)

Parse a requests content, should be from a PointCloud task source.

Parameters:

Name Type Description Default

data Link

buffer

The data source from a requests content.

required

Returns:

Type Description
ndarray

The parsed pointcloud with vertex coordinates sorted as XYZ.

Source code in plantdb/client/rest_api.py
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
def parse_requests_pcd(data):
    """Parse a requests content, should be from a PointCloud task source.

    Parameters
    ----------
    data : buffer
        The data source from a requests content.

    Returns
    -------
    numpy.ndarray
        The parsed pointcloud with vertex coordinates sorted as XYZ.
    """
    ## Read the pointcloud PLY as a `PlyData`:
    ply_pcd = PlyData.read(BytesIO(data))
    ## Convert the `PlyData`:
    return _ply_vertex_to_array(ply_pcd)

parse_requests_skeleton Link

parse_requests_skeleton(data)

Parse a requests content, should be from a CurveSkeleton task source.

Parameters:

Name Type Description Default

data Link

buffer

The data source from a requests content.

required

Returns:

Type Description
dict

The parsed skeleton with two entries: 'points' for points coordinates and 'lines' joining them.

Source code in plantdb/client/rest_api.py
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
def parse_requests_skeleton(data):
    """Parse a requests content, should be from a CurveSkeleton task source.

    Parameters
    ----------
    data : buffer
        The data source from a requests content.

    Returns
    -------
    dict
        The parsed skeleton with two entries: 'points' for points coordinates and 'lines' joining them.
    """
    return json.loads(data)

parse_requests_tree Link

parse_requests_tree(data)

Parse a requests content, should be from a TreeGraph task source.

Parameters:

Name Type Description Default

data Link

buffer

The data source from a requests content.

required

Returns:

Type Description
Graph

The loaded (tree) graph object.

Source code in plantdb/client/rest_api.py
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
def parse_requests_tree(data):
    """Parse a requests content, should be from a TreeGraph task source.

    Parameters
    ----------
    data : buffer
        The data source from a requests content.

    Returns
    -------
    networkx.Graph
        The loaded (tree) graph object.
    """
    import pickle
    tree = pickle.load(BytesIO(data))
    # FIXME: it would be better to return something that is JSON serializable...
    #  but the tree is not directed, so the `json_graph.tree_data` fails!
    # from networkx.readwrite import json_graph
    # data = json_graph.tree_data(tree, root=0)
    # return json.dumps(data)
    return tree

parse_scans_info Link

parse_scans_info(host, **kwargs)

Parse the information dictionary for all scans 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.

Returns:

Type Description
dict

The scan-id (dataset name) indexed information dictionary.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import parse_scans_info
>>> scan_dict = parse_scans_info('localhost', port=5000)
>>> print(sorted(scan_dict.keys()))
['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
Source code in plantdb/client/rest_api.py
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
def parse_scans_info(host, **kwargs):
    """Parse the information dictionary for all scans 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``.

    Returns
    -------
    dict
        The scan-id (dataset name) indexed information dictionary.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import parse_scans_info
    >>> scan_dict = parse_scans_info('localhost', port=5000)
    >>> print(sorted(scan_dict.keys()))
    ['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
    """
    scan_json = request_scans_info(host, **kwargs)
    scan_dict = {}
    for scan in scan_json:
        name = scan.pop('id')
        scan_dict[name] = scan
    return scan_dict

parse_task_images Link

parse_task_images(host, scan_id, task_name='images', size='orig', as_base64=False, **kwargs)

Get the list of images data for a given dataset and task name.

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 images for.

required

task_name Link

str

The name of the task to retrieve the images from. Defaults to 'images'.

'images'

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 chache;

'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.

Returns:

Type Description
list of PIL.Image

The list of PIL.Image from the PlantDB REST API.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import parse_task_images
>>> images = parse_task_images('localhost', 'real_plant', port=5000)
>>> print(len(images))
60
>>> img1 = images[0]
>>> print(img1.size)
(1440, 1080)
Source code in plantdb/client/rest_api.py
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
def parse_task_images(host, scan_id, task_name='images', size='orig', as_base64=False, **kwargs):
    """Get the list of images data for a given dataset and task name.

    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 images for.
    task_name : str, optional
        The name of the task to retrieve the images from. Defaults to 'images'.
    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 chache;
    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``.

    Returns
    -------
    list of PIL.Image
        The list of PIL.Image from the PlantDB REST API.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import parse_task_images
    >>> images = parse_task_images('localhost', 'real_plant', port=5000)
    >>> print(len(images))
    60
    >>> img1 = images[0]
    >>> print(img1.size)
    (1440, 1080)
    """
    images = []
    for img_uri in list_task_images_uri(host, scan_id, task_name, size, as_base64, **kwargs):
        images.append(
            Image.open(BytesIO(make_api_request(url=img_uri, session_token=kwargs.get('session_token', None)).content)))
    return images

parse_task_requests_data Link

parse_task_requests_data(task, data, extension=None)

Parse raw request data for a specified task.

The function selects an appropriate parser based on the provided extension (if any) or the task name, then applies that parser to the raw data payload. This is a small dispatcher that centralises the logic for choosing between the generic :func:parse_requests_json parser and any custom parsers defined in :data:PARSER_DICT and :data:EXT_PARSER_DICT.

Parameters:

Name Type Description Default

task Link

str

Identifier for the task whose data is being parsed. Used as a key to look up the default parser in :data:PARSER_DICT.

required

data Link

str or bytes

Raw payload that contains the request data. The parser returned by the dispatcher is expected to accept this type and convert it into a Python object (e.g. a dictionary).

required

extension Link

str

File‑extension or MIME‑type hint. If supplied, the parser is taken from :data:EXT_PARSER_DICT; otherwise the default parser for task is used.

None

Returns:

Type Description
Any

The result of the chosen parser applied to data. The exact type depends on the parser implementation (commonly a dict).

Examples:

>>> # Assume the following parsers are defined
>>> def parse_json(data): return {"parsed": data}
>>> PARSER_DICT = {"task1": parse_json}
>>> EXT_PARSER_DICT = {"txt": parse_json}
>>> # Example with task-based parser
>>> result = parse_task_requests_data("task1", '{"key": "value"}')
>>> print(result)
{'parsed': '{"key": "value"}'}
>>> # Example with extension-based parser
>>> result = parse_task_requests_data("unknown", "raw data", extension="txt")
>>> print(result)
{'parsed': 'raw data'}
Notes
  • The function does not perform any validation of data; it delegates all parsing logic to the chosen parser.
  • If task is not found in :data:PARSER_DICT and extension is None, the fallback parser :func:parse_requests_json is used.
See Also

parse_requests_json : Default JSON parser used when no task matches.

Source code in plantdb/client/rest_api.py
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
def parse_task_requests_data(task, data, extension=None):
    """Parse raw request data for a specified task.

    The function selects an appropriate parser based on the provided
    *extension* (if any) or the *task* name, then applies that parser
    to the raw *data* payload.  This is a small dispatcher that
    centralises the logic for choosing between the generic
    :func:`parse_requests_json` parser and any custom parsers defined
    in :data:`PARSER_DICT` and :data:`EXT_PARSER_DICT`.

    Parameters
    ----------
    task : str
        Identifier for the task whose data is being parsed.  Used as a
        key to look up the default parser in :data:`PARSER_DICT`.
    data : str or bytes
        Raw payload that contains the request data.  The parser returned
        by the dispatcher is expected to accept this type and convert it
        into a Python object (e.g. a dictionary).
    extension : str, optional
        File‑extension or MIME‑type hint.  If supplied, the parser is
        taken from :data:`EXT_PARSER_DICT`; otherwise the default parser
        for *task* is used.

    Returns
    -------
    Any
        The result of the chosen parser applied to *data*.  The exact
        type depends on the parser implementation (commonly a dict).

    Examples
    --------
    >>> # Assume the following parsers are defined
    >>> def parse_json(data): return {"parsed": data}
    >>> PARSER_DICT = {"task1": parse_json}
    >>> EXT_PARSER_DICT = {"txt": parse_json}
    >>> # Example with task-based parser
    >>> result = parse_task_requests_data("task1", '{"key": "value"}')
    >>> print(result)
    {'parsed': '{"key": "value"}'}
    >>> # Example with extension-based parser
    >>> result = parse_task_requests_data("unknown", "raw data", extension="txt")
    >>> print(result)
    {'parsed': 'raw data'}

    Notes
    -----
    - The function does not perform any validation of *data*; it
      delegates all parsing logic to the chosen parser.
    - If *task* is not found in :data:`PARSER_DICT` and *extension* is
      ``None``, the fallback parser :func:`parse_requests_json` is used.

    See Also
    --------
    parse_requests_json : Default JSON parser used when no task matches.
    """
    if extension is not None:
        data_parser = EXT_PARSER_DICT[extension]
    else:
        data_parser = PARSER_DICT.get(task, parse_requests_json)
    return data_parser(data)

plantdb_url Link

plantdb_url(host, port=PLANTDB_PORT, prefix=PLANTDB_PREFIX, ssl=False)

Generates the URL for the PlantDB REST API using the specified host and port.

This function constructs a URL by combining the provided host, port, prefix, and SSL settings.

Parameters:

Name Type Description Default

host Link

str

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

required

port Link

int or str

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

PLANTDB_PORT

prefix Link

str

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

PLANTDB_PREFIX

ssl Link

bool

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

False

Returns:

Type Description
str

A properly formatted URL for the PlantDB REST API.

Notes
  • The function ensures that the prefix is correctly formatted by stripping leading and trailing slashes.
  • The SSL flag determines whether 'http' or 'https' is used in the URL scheme.

Examples:

>>> from plantdb.client.rest_api import plantdb_url
>>> plantdb_url('localhost')
'http://localhost'
>>> plantdb_url('api.example.com', port=8443, ssl=True)
'https://api.example.com:8443'
>>> plantdb_url('localhost', port=5000, prefix='/plantdb', ssl=True)
'https://localhost:5000/plantdb/'
Source code in plantdb/client/rest_api.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def plantdb_url(host, port=PLANTDB_PORT, prefix=PLANTDB_PREFIX, ssl=False) -> str:
    """Generates the URL for the PlantDB REST API using the specified host and port.

    This function constructs a URL by combining the provided host, port, prefix, and SSL settings.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``None``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        If provided, it will be added to the end of the URL.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (``True``) or HTTP (``False``). Defaults to ``False``.

    Returns
    -------
    str
        A properly formatted URL for the PlantDB REST API.

    Notes
    -----
    - The function ensures that the prefix is correctly formatted by stripping leading and trailing slashes.
    - The SSL flag determines whether 'http' or 'https' is used in the URL scheme.

    Examples
    --------
    >>> from plantdb.client.rest_api import plantdb_url
    >>> plantdb_url('localhost')
    'http://localhost'
    >>> plantdb_url('api.example.com', port=8443, ssl=True)
    'https://api.example.com:8443'
    >>> plantdb_url('localhost', port=5000, prefix='/plantdb', ssl=True)
    'https://localhost:5000/plantdb/'
    """
    origin = origin_url(host, port, ssl)

    # Format the prefix by stripping leading and trailing slashes and adding a leading slash
    if prefix:
        prefix = '/' + prefix.lstrip('/').rstrip('/') + '/'
    else:
        prefix = ''

    return f"{origin}{prefix}"

refresh_url Link

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

Generates a formatted URL for refreshing a specific dataset or the entire database.

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 for which the refresh URL needs to be generated. If not provided, the refresh URL for the entire server is returned instead. Defaults to None.

None

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
str

A correctly formatted URL for refreshing the specified dataset or the entire PlantDB REST API server.

Examples:

>>> from plantdb.client.rest_api import refresh_url
>>> refresh_url('localhost', "real_plant")
'http://localhost/refresh?scan_id=real_plant'
>>> refresh_url('localhost', "real_plant", prefix='/plantdb')
'http://localhost/plantdb/refresh?scan_id=real_plant'
Source code in plantdb/client/rest_api.py
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
def refresh_url(host, scan_id=None, **kwargs):
    """Generates a formatted URL for refreshing a specific dataset or the entire database.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str or None, optional
        The name of the dataset for which the refresh URL needs to be generated.
        If not provided, the refresh URL for the entire server is returned instead.
        Defaults to ``None``.

    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
    -------
    str
        A correctly formatted URL for refreshing the specified dataset or the entire PlantDB REST API server.

    Examples
    --------
    >>> from plantdb.client.rest_api import refresh_url
    >>> refresh_url('localhost', "real_plant")
    'http://localhost/refresh?scan_id=real_plant'
    >>> refresh_url('localhost', "real_plant", prefix='/plantdb')
    'http://localhost/plantdb/refresh?scan_id=real_plant'
    """
    url = origin_url(host, **kwargs)
    return join_url(url, api_endpoints.refresh(scan_id, **kwargs))

register_url Link

register_url(host, **kwargs)

Generate the full URL for the PlantDB API register endpoint.

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.

Returns:

Type Description
str

The fully qualified register URL as a string.

Examples:

>>> from plantdb.client.rest_api import logout_url
>>> # Basic usage with default configuration
>>> url = logout_url('localhost')
>>> print(url)
http://localhost/logout
>>> # Specify a custom prefix and enable SSL
>>> url = logout_url('dev.romi.local', prefix="/plantdb", ssl=True)
>>> print(url)
https://dev.romi.local/plantdb/logout
Source code in plantdb/client/rest_api.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
def register_url(host, **kwargs):
    """Generate the full URL for the PlantDB API register endpoint.

    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``.

    Returns
    -------
    str
        The fully qualified register URL as a string.

    Examples
    --------
    >>> from plantdb.client.rest_api import logout_url
    >>> # Basic usage with default configuration
    >>> url = logout_url('localhost')
    >>> print(url)
    http://localhost/logout
    >>> # Specify a custom prefix and enable SSL
    >>> url = logout_url('dev.romi.local', prefix="/plantdb", ssl=True)
    >>> print(url)
    https://dev.romi.local/plantdb/logout
    """
    url = origin_url(host, **kwargs)
    return join_url(url, api_endpoints.register(**kwargs))

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 import request_login
>>> from plantdb.client.rest_api 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.py
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
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 import request_login
    >>> from plantdb.client.rest_api 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 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.py
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
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 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 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.py
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
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 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 import request_check_username
>>> username_exists = request_check_username('localhost', 'admin', port=5000)
>>> print(username_exists)
True
Source code in plantdb/client/rest_api.py
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
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 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 import request_dataset_file_upload
>>> request_dataset_file_upload(host, 'arabidopsis000', '/path/to/local/file.txt')
Source code in plantdb/client/rest_api.py
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
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 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 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.py
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
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 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 import request_login
>>> from plantdb.client.rest_api 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.py
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
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 import request_login
    >>> from plantdb.client.rest_api 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 import request_login
>>> from plantdb.client.rest_api import request_logout
>>> from plantdb.client.rest_api 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.py
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
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 import request_login
    >>> from plantdb.client.rest_api import request_logout
    >>> from plantdb.client.rest_api 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 import request_refresh
>>> success, message = request_refresh('localhost', "arabidopsis000", port = 5000)
>>> print(message)
Successfully reloaded scan 'arabidopsis000'
Source code in plantdb/client/rest_api.py
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
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 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 import request_scan_data
>>> from plantdb.client.rest_api 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.py
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
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 import request_scan_data
    >>> from plantdb.client.rest_api 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 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.py
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
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 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 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.py
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
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 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 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.py
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
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 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 import request_scans_info
>>> from plantdb.client.rest_api 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.py
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
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 import request_scans_info
    >>> from plantdb.client.rest_api 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 import request_login
>>> from plantdb.client.rest_api 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.py
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
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 import request_login
    >>> from plantdb.client.rest_api 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 import request_login
>>> from plantdb.client.rest_api 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.py
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
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 import request_login
    >>> from plantdb.client.rest_api 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()

scan_config_url Link

scan_config_url(host, scan_id, cfg_fname='scan.toml', **kwargs)

Return the scan URL to access the scanning configuration file.

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.

required

cfg_fname Link

str

The name of the TOML scan file, defaults to 'scan.toml'.

'scan.toml'

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
str

The URL to the scanning configuration file.

Examples:

>>> from plantdb.client.rest_api import scan_config_url
>>> scan_config_url('localhost', 'real_plant')
'http://localhost/files/real_plant/scan.toml'
>>> scan_config_url('localhost', 'real_plant', prefix='/plantdb')
'http://localhost/plantdb/files/real_plant/scan.toml'
Source code in plantdb/client/rest_api.py
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
def scan_config_url(host, scan_id, cfg_fname='scan.toml', **kwargs):
    """Return the scan URL to access the scanning configuration file.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str
        The name of the dataset.
    cfg_fname : str, optional
        The name of the TOML scan file, defaults to ``'scan.toml'``.

    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
    -------
    str
        The URL to the scanning configuration file.

    Examples
    --------
    >>> from plantdb.client.rest_api import scan_config_url
    >>> scan_config_url('localhost', 'real_plant')
    'http://localhost/files/real_plant/scan.toml'
    >>> scan_config_url('localhost', 'real_plant', prefix='/plantdb')
    'http://localhost/plantdb/files/real_plant/scan.toml'
    """
    return scan_file_url(host, scan_id, cfg_fname, **kwargs)

scan_file_url Link

scan_file_url(host, scan_id, file_path, **kwargs)

Build the URL for accessing a dataset file.

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.

required

file_path Link

str

The path to the file in the databse.

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
str

The complete URL for the dataset file.

Source code in plantdb/client/rest_api.py
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
def scan_file_url(host, scan_id, file_path, **kwargs):
    """Build the URL for accessing a dataset file.

    Parameters
    ----------
    host : str
        The hostname or IP address of the PlantDB REST API server.
    scan_id : str
        The name of the dataset.
    file_path : str
        The path to the file in the databse.

    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
    -------
    str
        The complete URL for the dataset file.
    """
    url = origin_url(host, **kwargs)
    return join_url(url, api_endpoints.file_path(scan_id, file_path, **kwargs))

scan_image_url Link

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

Get the URL to 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.

Returns:

Type Description
str

The URL to an image of a scan dataset and task fileset.

Examples:

>>> from plantdb.client.rest_api import scan_image_url
>>> scan_image_url('localhost', "real_plant", "images", "00000_rgb")
'http://localhost/image/real_plant/images/00000_rgb?size=orig'
>>> scan_image_url('localhost', "real_plant", "images", "00000_rgb", as_base64=True)
'http://localhost/image/real_plant/images/00000_rgb?size=orig&as_base64=true'
>>> scan_image_url('localhost', "real_plant", "images", "00000_rgb", prefix='/plantdb')
'http://localhost/plantdb/image/real_plant/images/00000_rgb?size=orig'
Source code in plantdb/client/rest_api.py
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
def scan_image_url(host, scan_id, fileset_id, file_id, size='orig', as_base64=False, **kwargs):
    """Get the URL to 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``.


    Returns
    -------
    str
        The URL to an image of a scan dataset and task fileset.

    Examples
    --------
    >>> from plantdb.client.rest_api import scan_image_url
    >>> scan_image_url('localhost', "real_plant", "images", "00000_rgb")
    'http://localhost/image/real_plant/images/00000_rgb?size=orig'
    >>> scan_image_url('localhost', "real_plant", "images", "00000_rgb", as_base64=True)
    'http://localhost/image/real_plant/images/00000_rgb?size=orig&as_base64=true'
    >>> scan_image_url('localhost', "real_plant", "images", "00000_rgb", prefix='/plantdb')
    'http://localhost/plantdb/image/real_plant/images/00000_rgb?size=orig'
    """
    url = origin_url(host, **kwargs)
    return join_url(url, api_endpoints.image(scan_id, fileset_id, file_id, size, as_base64, **kwargs))

scan_preview_image_url Link

scan_preview_image_url(host, scan_id, size='thumb', **kwargs)

Get the URL to the preview image for a scan dataset 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

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 'thumb', 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'

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
str

The URL to the preview image for a scan dataset.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import scan_preview_image_url
>>> img_url = scan_preview_image_url('localhost', 'real_plant')
>>> print(img_url)
http://localhost/image/real_plant/images/00000_rgb?size=thumb
>>> img_url = scan_preview_image_url('localhost', 'real_plant', size=100)
>>> print(img_url)
http://localhost/image/real_plant/images/00000_rgb?size=100
>>> # Download and display the image
>>> import requests
>>> from PIL import Image
>>> from io import BytesIO
>>> response = requests.get(img_url)  # Send a GET request to the URL
>>> image = Image.open(BytesIO(response.content))  # Open the image from the bytes data
>>> image.show()  # Display the image
Source code in plantdb/client/rest_api.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
def scan_preview_image_url(host, scan_id, size="thumb", **kwargs):
    """Get the URL to the preview image for a scan dataset 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.
    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 ``'thumb'``, 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;

    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
    -------
    str
        The URL to the preview image for a scan dataset.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import scan_preview_image_url
    >>> img_url = scan_preview_image_url('localhost', 'real_plant')
    >>> print(img_url)
    http://localhost/image/real_plant/images/00000_rgb?size=thumb
    >>> img_url = scan_preview_image_url('localhost', 'real_plant', size=100)
    >>> print(img_url)
    http://localhost/image/real_plant/images/00000_rgb?size=100
    >>> # Download and display the image
    >>> import requests
    >>> from PIL import Image
    >>> from io import BytesIO
    >>> response = requests.get(img_url)  # Send a GET request to the URL
    >>> image = Image.open(BytesIO(response.content))  # Open the image from the bytes data
    >>> image.show()  # Display the image
    """
    from plantdb.client.api_endpoints import sanitize_name
    scan_id = sanitize_name(scan_id)
    scan_names = request_scan_names_list(host, **kwargs)
    if scan_id not in scan_names:
        return None

    thumb_uri = request_scan_data(host, scan_id, **kwargs)["thumbnailUri"]
    if size != "thumb":
        thumb_uri = thumb_uri.replace("size=thumb", f"size={size}")
    url = origin_url(host, **kwargs)
    return join_url(url, thumb_uri)

scan_reconstruction_url Link

scan_reconstruction_url(host, scan_id, cfg_fname='pipeline.toml', **kwargs)

Return the scan URL to access the reconstruction configuration file.

Parameters:

Name Type Description Default

scan_id Link

str

The name of the dataset.

required

cfg_fname Link

str

The name of the TOML scan file, defaults to 'pipeline.toml'.

'pipeline.toml'

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
str

The URL to the reconstruction configuration file.

Examples:

>>> from plantdb.client.rest_api import scan_reconstruction_url
>>> scan_reconstruction_url('localhost', 'real_plant')
'http://localhost/files/real_plant/pipeline.toml'
>>> scan_reconstruction_url('localhost', 'real_plant', prefix='/plantdb')
'http://localhost/plantdb/files/real_plant/pipeline.toml'
Source code in plantdb/client/rest_api.py
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
def scan_reconstruction_url(host, scan_id, cfg_fname='pipeline.toml', **kwargs):
    """Return the scan URL to access the reconstruction configuration file.

    Parameters
    ----------
    scan_id : str
        The name of the dataset.
    cfg_fname : str, optional
        The name of the TOML scan file, defaults to ``'pipeline.toml'``.

    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
    -------
    str
        The URL to the reconstruction configuration file.

    Examples
    --------
    >>> from plantdb.client.rest_api import scan_reconstruction_url
    >>> scan_reconstruction_url('localhost', 'real_plant')
    'http://localhost/files/real_plant/pipeline.toml'
    >>> scan_reconstruction_url('localhost', 'real_plant', prefix='/plantdb')
    'http://localhost/plantdb/files/real_plant/pipeline.toml'
    """
    return scan_file_url(host, scan_id, cfg_fname, **kwargs)

scan_url Link

scan_url(host, scan_id, **kwargs)

Generates the URL pointing to the scan JSON from the PlantDB REST API.

Parameters:

Name Type Description Default

scan_id Link

str

The name of the scan dataset to retrieve the JSON from.

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
str

A properly formatted URL of the PlantDB REST API pointing to the scans list.

Examples:

>>> from plantdb.client.rest_api import scan_url
>>> scan_url('localhost', "real_plant")
'http://localhost/scan/real_plant'
>>> scan_url('localhost', "real_plant", prefix='/plantdb')
'http://localhost/plantdb/scan/real_plant'
Source code in plantdb/client/rest_api.py
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
def scan_url(host, scan_id, **kwargs):
    """Generates the URL pointing to the scan JSON from the PlantDB REST API.

    Parameters
    ----------
    scan_id : str
        The name of the scan dataset to retrieve the JSON from.

    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
    -------
    str
        A properly formatted URL of the PlantDB REST API pointing to the scans list.

    Examples
    --------
    >>> from plantdb.client.rest_api import scan_url
    >>> scan_url('localhost', "real_plant")
    'http://localhost/scan/real_plant'
    >>> scan_url('localhost', "real_plant", prefix='/plantdb')
    'http://localhost/plantdb/scan/real_plant'
    """
    url = origin_url(host, **kwargs)
    return join_url(url, api_endpoints.scan(scan_id, **kwargs))

scans_url Link

scans_url(host, **kwargs)

Generates the URL listing the scans 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

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
str

A properly formatted URL of the PlantDB REST API pointing to the scans list.

Examples:

>>> from plantdb.client.rest_api import scans_url
>>> scans_url('127.0.0.1')
'http://127.0.0.1/scans'
>>> scans_url('localhost', prefix='/plantdb')
'http://localhost/plantdb/scans'
>>> scans_url('dev.romi.local', prefix='/plantdb/', ssl=True)
'https://dev.romi.local/plantdb/scans'
Source code in plantdb/client/rest_api.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def scans_url(host, **kwargs):
    """Generates the URL listing the scans from 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``.

    Returns
    -------
    str
        A properly formatted URL of the PlantDB REST API pointing to the scans list.

    Examples
    --------
    >>> from plantdb.client.rest_api import scans_url
    >>> scans_url('127.0.0.1')
    'http://127.0.0.1/scans'
    >>> scans_url('localhost', prefix='/plantdb')
    'http://localhost/plantdb/scans'
    >>> scans_url('dev.romi.local', prefix='/plantdb/', ssl=True)
    'https://dev.romi.local/plantdb/scans'
    """
    url = origin_url(host, **kwargs)
    return join_url(url, api_endpoints.scans(**kwargs))

token_refresh_url Link

token_refresh_url(host, **kwargs)

Generate the full URL for the PlantDB API token refresh endpoint.

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.

Returns:

Type Description
str

The fully qualified register URL as a string.

Examples:

>>> from plantdb.client.rest_api import token_refresh_url
>>> # Basic usage with default configuration
>>> url = token_refresh_url('localhost')
>>> print(url)
http://localhost/token-refresh
Source code in plantdb/client/rest_api.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
def token_refresh_url(host, **kwargs):
    """Generate the full URL for the PlantDB API token refresh endpoint.

    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``.

    Returns
    -------
    str
        The fully qualified register URL as a string.

    Examples
    --------
    >>> from plantdb.client.rest_api import token_refresh_url
    >>> # Basic usage with default configuration
    >>> url = token_refresh_url('localhost')
    >>> print(url)
    http://localhost/token-refresh
    """
    url = origin_url(host, **kwargs)
    return join_url(url, api_endpoints.token_refresh())

token_validation_url Link

token_validation_url(host, **kwargs)

Generate the full URL for the PlantDB API token validation endpoint.

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.

Returns:

Type Description
str

The fully qualified register URL as a string.

Examples:

>>> from plantdb.client.rest_api import token_validation_url
>>> # Basic usage with default configuration
>>> url = token_validation_url('localhost')
>>> print(url)
http://localhost/token-validation
Source code in plantdb/client/rest_api.py
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
def token_validation_url(host, **kwargs):
    """Generate the full URL for the PlantDB API token validation endpoint.

    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``.

    Returns
    -------
    str
        The fully qualified register URL as a string.

    Examples
    --------
    >>> from plantdb.client.rest_api import token_validation_url
    >>> # Basic usage with default configuration
    >>> url = token_validation_url('localhost')
    >>> print(url)
    http://localhost/token-validation
    """
    url = origin_url(host, **kwargs)
    return join_url(url, api_endpoints.token_validation())