Skip to content

scan

Scan REST API ResourcesLink

Provides Flask-RESTful resources for managing scan datasets in PlantDB. The resources expose endpoints that allow clients to list scans, retrieve detailed information, create new scans, and manipulate scan metadata and filesets. These APIs simplify integration with PlantDB by handling request parsing, security (rate-limiting and JWT extraction), and data sanitization.

Key FeaturesLink

  • ScansList: Returns a list of scan identifiers with optional JSON-based filtering and fuzzy matching.
  • ScansTable: Supplies detailed information (metadata, tasks, files) for each scan, supporting the same filtering capabilities.
  • Scan: Retrieves or creates a single scan, performing ID sanitization and returning comprehensive scan data.
  • ScanCreate: Dedicated endpoint for creating new scans with optional metadata.
  • ScanMetadata: GET/POST endpoints to read and update a scan’s metadata, with support for partial updates or full replacement.
  • ScanFilesets: Lists filesets contained in a scan, also supporting query filtering and fuzzy matching.
  • Security Integration: Leverages JWT-based authentication via the @add_jwt_from_header decorator to ensure secure access to file operations.

Usage ExamplesLink

Below is a minimal example that demonstrates how to register the ScansList resource with a Flask-RESTful application.

>>> import logging
>>> from flask import Flask
>>> from flask_restful import Api
>>> from plantdb.server.api.scan import ScansList
>>> from plantdb.commons.auth.session import JWTSessionManager
>>> from plantdb.commons.fsdb.core import FSDB
>>> from plantdb.commons.test_database import setup_test_database
>>> # Create a Flask application
>>> app = Flask(__name__)
>>> # Create a logger
>>> logger = logging.getLogger("plantdb.scan")
>>> logger.setLevel(logging.INFO)
>>> # Initialize a test database with a JWTSessionManager
>>> db_path = setup_test_database('real_plant')
>>> mgr = JWTSessionManager()
>>> db = FSDB(db_path, session_manager=mgr)
>>> db.connect()
>>> # RESTful API and resource registration
>>> api = Api(app)
>>> api.add_resource(ScansList, "/scans", resource_class_kwargs={"db": db})
>>> # Start the APP
>>> app.run(host='0.0.0.0', port=5000)

It may be used as follows (in another Python REPL):

>>> import requests
>>> # List all scans
>>> response = requests.get("http://127.0.0.1:5000/scans")
>>> scans = response.json()
>>> print(scans)
['real_plant_analyzed', 'real_plant', 'virtual_plant_analyzed', 'virtual_plant']
>>> # Run a filtered, fuzzy search on metadata
>>> query = {"object": {"environment":"Lyon.*"}}
>>> response = requests.get("http://127.0.0.1:5000/scans", params= {"filterQuery": query, "fuzzy": "true"})
>>> filtered_scans = response.json()
>>> print(filtered_scans)  # list of scan IDs matching the filter
['real_plant_analyzed', 'real_plant']

Scan Link

Scan(db, logger=None, deploy_prefix='')

Bases: Resource

A RESTful resource class for serving scan dataset information.

This class handles HTTP GET requests for scan datasets, providing detailed information about the scan, including metadata, file locations, and task status.

Attributes:

Name Type Description
db FSDB

The database providing the resources to serve.

logger Logger

The logger used to record operations and errors.

Notes

The class sanitizes scan IDs before processing requests to ensure security. All responses are returned as JSON-serializable dictionaries.

See Also

plantdb.server.services.scan.get_scan_info : Function used to collect and format scan information plantdb.server.core.security.sanitize_name : Function used to validate and clean scan IDs

Initialize the resource.

Parameters:

Name Type Description Default

db Link

FSDB

A database instance providing the resources to serve.

required

logger Link

Logger

A logger instance to record operations and errors.

None

deploy_prefix Link

str

Deployment (reverse-proxy) prefix prepended before /api/v1/... when generating endpoint URLs in scan responses.

''
Source code in plantdb/server/api/scan.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
def __init__(self, db, logger=None, deploy_prefix=""):
    """Initialize the resource.

    Parameters
    ----------
    db : plantdb.commons.fsdb.core.FSDB
        A database instance providing the resources to serve.
    logger : logging.Logger
        A logger instance to record operations and errors.
    deploy_prefix : str, optional
        Deployment (reverse-proxy) prefix prepended before ``/api/v1/...``
        when generating endpoint URLs in scan responses.
    """
    self.db: FSDB = db
    self.logger: logging.Logger = logger if logger else get_logger(self.__class__.__name__)
    self.deploy_prefix: str = deploy_prefix

get Link

get(scan_id, **kwargs)

Retrieve detailed information about a specific scan dataset.

Parameters:

Name Type Description Default

scan_id Link

str

Identifier for the scan dataset. Must contain only alphanumeric characters, underscores, dashes, or periods.

required

Returns:

Type Description
dict

A dictionary containing scan information with the following keys:

- 'metadata' (dict): Contains scan date, object information, and image count
- 'files' (dict): Contains paths to related files and archives
- 'tasks' (dict): Contains information about processing task status
- 'thumbnail' (str): URI to the scan's thumbnail image

Raises:

Type Description
ValueError

If the scan_id contains invalid characters

NotFoundError

If the specified scan does not exist in the database

HTTPException

If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client.

Examples:

>>> # Start the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> # Get detailed information about a specific dataset
>>> response = requests.get("http://127.0.0.1:5000" + api_endpoints.scan('real_plant'))
>>> scan_data = response.json()
>>> # Access metadata information
>>> print(scan_data['metadata']['nbPhotos'])
60
Source code in plantdb/server/api/scan.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
@sanitize_ids('scan_id')
@rate_limit(max_requests=120, window_seconds=60)
@add_jwt_from_header
@use_guest_as_default  # FIXME: Remove this if we want strict token identification
def get(self, scan_id, **kwargs):
    """Retrieve detailed information about a specific scan dataset.

    Parameters
    ----------
    scan_id : str
        Identifier for the scan dataset. Must contain only alphanumeric
        characters, underscores, dashes, or periods.

    Returns
    -------
    dict
        A dictionary containing scan information with the following keys:

            - 'metadata' (dict): Contains scan date, object information, and image count
            - 'files' (dict): Contains paths to related files and archives
            - 'tasks' (dict): Contains information about processing task status
            - 'thumbnail' (str): URI to the scan's thumbnail image

    Raises
    ------
    ValueError
        If the scan_id contains invalid characters
    NotFoundError
        If the specified scan does not exist in the database
    http.client.HTTPException
         If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client.

    Examples
    --------
    >>> # Start the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> # Get detailed information about a specific dataset
    >>> response = requests.get("http://127.0.0.1:5000" + api_endpoints.scan('real_plant'))
    >>> scan_data = response.json()
    >>> # Access metadata information
    >>> print(scan_data['metadata']['nbPhotos'])
    60
    """
    try:
        scan = self.db.get_scan(scan_id, **kwargs)
        scan_info = get_scan_info(scan, logger=self.logger, prefix=self.deploy_prefix)

    except NoAuthUserError as e:
        return {'error': str(e)}, 401  # HTTP 401 Unauthorized (authentication)
    except ScanNotFoundError as e:
        return {'error': str(e)}, 404  # HTTP 404 Not Found
    except Exception as e:
        return {'error': f"Error while accessing '{scan_id}': {str(e)}"}, 404  # HTTP 404 Not Found
    else:
        return scan_info, 200

post Link

post(scan_id, **kwargs)

Create a new scan dataset.

Parameters:

Name Type Description Default

scan_id Link

str

Identifier for the new scan dataset. Must contain only alphanumeric characters, underscores, dashes, or periods.

required

Returns:

Type Description
dict

A dictionary containing the response with the following possible structures:

- On success: {'message': 'Scan created successfully', 'id': scan_id}
- On error: {'error': error_message}

Raises:

Type Description
HTTPException

If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client.

Notes

The request body accepts a JSON object containing:

- 'metadata' (dict): the new metadata

Examples:

>>> # Start the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> # Start by log in as 'admin'
>>> user_data = {'username': 'admin', 'password': 'admin'}
>>> login_res = requests.post("http://127.0.0.1:5000" + api_endpoints.login(), json=user_data)
>>> token = login_res.json()['access_token']
>>> # Create a new scan dataset
>>> url = "http://127.0.0.1:5000" + api_endpoints.scan("test_scan_001")
>>> response = requests.post(url, headers={'Authorization': 'Bearer ' + token})
>>> print(response.ok)
True
>>> scan_data = response.json()
>>> print(scan_data['id'])
test_scan_001
>>> # Create a new scan dataset with metadata
>>> md = {'metadata': {'test_metadata': True}}
>>> url = "http://127.0.0.1:5000" + api_endpoints.scan("test_scan_md")
>>> response = requests.post(url, json=md, headers={'Authorization': 'Bearer ' + token})
>>> print(response.ok)
>>> print(response.json()['id'])
test_scan_md
>>> url = "http://127.0.0.1:5000" + api_endpoints.scan_metadata("test_scan_md")
>>> response = requests.get(url)
>>> response.json()['metadata']['test_metadata']
True
>>> _ = requests.post("http://127.0.0.1:5000" + api_endpoints.logout())  # logout
>>> # Stop the test server
>>> server.stop()
Source code in plantdb/server/api/scan.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
@rate_limit(max_requests=15, window_seconds=60)
@sanitize_ids('scan_id')
@add_jwt_from_header
def post(self, scan_id, **kwargs):
    """Create a new scan dataset.

    Parameters
    ----------
    scan_id : str
        Identifier for the new scan dataset.
        Must contain only alphanumeric characters, underscores, dashes, or periods.

    Returns
    -------
    dict
        A dictionary containing the response with the following possible structures:

            - On success: {'message': 'Scan created successfully', 'id': scan_id}
            - On error: {'error': error_message}

    Raises
    ------
    http.client.HTTPException
         If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client.

    Notes
    -----
    The request body accepts a JSON object containing:

        - 'metadata' (dict): the new metadata

    Examples
    --------
    >>> # Start the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> # Start by log in as 'admin'
    >>> user_data = {'username': 'admin', 'password': 'admin'}
    >>> login_res = requests.post("http://127.0.0.1:5000" + api_endpoints.login(), json=user_data)
    >>> token = login_res.json()['access_token']
    >>> # Create a new scan dataset
    >>> url = "http://127.0.0.1:5000" + api_endpoints.scan("test_scan_001")
    >>> response = requests.post(url, headers={'Authorization': 'Bearer ' + token})
    >>> print(response.ok)
    True
    >>> scan_data = response.json()
    >>> print(scan_data['id'])
    test_scan_001
    >>> # Create a new scan dataset with metadata
    >>> md = {'metadata': {'test_metadata': True}}
    >>> url = "http://127.0.0.1:5000" + api_endpoints.scan("test_scan_md")
    >>> response = requests.post(url, json=md, headers={'Authorization': 'Bearer ' + token})
    >>> print(response.ok)
    >>> print(response.json()['id'])
    test_scan_md
    >>> url = "http://127.0.0.1:5000" + api_endpoints.scan_metadata("test_scan_md")
    >>> response = requests.get(url)
    >>> response.json()['metadata']['test_metadata']
    True
    >>> _ = requests.post("http://127.0.0.1:5000" + api_endpoints.logout())  # logout
    >>> # Stop the test server
    >>> server.stop()
    """
    # Get JSON data from request
    data = request.get_json(silent=True)
    # Get metadata if provided
    if data:
        metadata = data.get('metadata', None)
    else:
        metadata = None

    try:
        # Attempt to create a new scan in the database with the given scan_id
        scan = self.db.create_scan(scan_id, metadata=metadata, **kwargs)
        # Check if scan creation was successful
        if scan is None:
            self.logger.error(f"Failed to create scan: {scan_id}")
            return {'error': 'Failed to create scan'}, 500  # HTTP 500 Internal Server Error
        self.logger.info(f"Successfully created scan: {scan_id}")

    except NoAuthUserError as e:
        return {'error': str(e)}, 401  # HTTP 401 Unauthorized (authentication)
    except ScanExistsError as e:
        return {'error': str(e)}, 409  # HTTP 409 Conflict
    except TimeLapseNotFoundError as e:
        return {'error': str(e)}, 404  # HTTP 404 Not Found (missing timelapse)
    except Exception as e:
        # Handle all other exceptions including duplicate scans
        self.logger.error(f"Error creating scan {scan_id}: {str(e)}")
        # Return generic server error for all other exceptions
        return {'error': f'Internal server error: {str(e)}'}, 500  # HTTP 500 Internal Server Error
    else:
        self.db.reload(scan_id)  # load the newly created scan
        # Return success response with HTTP 201 (Created) status code
        return {'message': 'Scan created successfully', 'id': scan.id}, 201

ScanFilesets Link

ScanFilesets(db, logger=None)

Bases: Resource

REST API resource for managing scan filesets operations.

This class provides endpoints to interact with filesets within a scan. It allows listing filesets with optional query filtering and fuzzy matching capabilities.

Attributes:

Name Type Description
db FSDB

The database providing the resources to serve.

logger Logger

The logger used to record operations and errors.

Initialize the resource.

Parameters:

Name Type Description Default

db Link

FSDB

A database instance providing the resources to serve.

required

logger Link

Logger

A logger instance to record operations and errors.

None
Source code in plantdb/server/api/scan.py
767
768
769
770
771
772
773
774
775
776
777
778
def __init__(self, db, logger=None):
    """Initialize the resource.

    Parameters
    ----------
    db : plantdb.commons.fsdb.core.FSDB
        A database instance providing the resources to serve.
    logger : logging.Logger
        A logger instance to record operations and errors.
    """
    self.db: FSDB = db
    self.logger: logging.Logger = logger if logger else get_logger(self.__class__.__name__)

get Link

get(scan_id, **kwargs)

List all filesets in a specified scan.

This method retrieves the list of filesets contained in a scan using the list_filesets() method from plantdb.commons.fsdb.core.Scan.

Parameters:

Name Type Description Default

scan_id Link

str

The ID of the scan.

required

Returns:

Type Description
dict

Response containing either: - On success (200): {'filesets': list of fileset IDs} - On error (404, 500): {'error': error description}

int

HTTP status code (200, 404, or 500)

Examples:

>>> # Start the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> # List filesets in a scan:
>>> url = "http://127.0.0.1:5000/" + api_endpoints.scan_filesets_list("real_plant")
>>> response = requests.get(url)
>>> print(response.ok)
True
>>> print(response.json())
{'filesets': ['images']}
>>> url = "http://127.0.0.1:5000/" + api_endpoints.scan_filesets_list("real_plant_analyzed")
>>> response = requests.get(url)
>>> print(len(response.json()['filesets']))  # Get the number of filesets
10
>>> # Stop the test server
>>> server.stop()
Source code in plantdb/server/api/scan.py
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
@sanitize_ids('scan_id')
@add_jwt_from_header
@use_guest_as_default  # FIXME: Remove this if we want strict token identification
def get(self, scan_id, **kwargs):
    """List all filesets in a specified scan.

    This method retrieves the list of filesets contained in a scan using the
    `list_filesets()` method from `plantdb.commons.fsdb.core.Scan`.

    Parameters
    ----------
    scan_id : str
        The ID of the scan.

    Returns
    -------
    dict
        Response containing either:
          - On success (200): {'filesets': list of fileset IDs}
          - On error (404, 500): {'error': error description}
    int
        HTTP status code (200, 404, or 500)

    Examples
    --------
    >>> # Start the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> # List filesets in a scan:
    >>> url = "http://127.0.0.1:5000/" + api_endpoints.scan_filesets_list("real_plant")
    >>> response = requests.get(url)
    >>> print(response.ok)
    True
    >>> print(response.json())
    {'filesets': ['images']}
    >>> url = "http://127.0.0.1:5000/" + api_endpoints.scan_filesets_list("real_plant_analyzed")
    >>> response = requests.get(url)
    >>> print(len(response.json()['filesets']))  # Get the number of filesets
    10
    >>> # Stop the test server
    >>> server.stop()
    """
    # Get fuzzy parameter from request URL
    fuzzy = request.args.get('fuzzy', False, type=bool)
    # Get filter query from "filterQuery" JSON data
    query_data = request.get_json(silent=True)
    if isinstance(query_data, dict):
        query = query_data.get("filterQuery")
    else:
        query = None

    try:
        # Get the scan
        scan = self.db.get_scan(scan_id, **kwargs)
        # Get the list of filesets
        filesets = scan.list_filesets(query=query, fuzzy=fuzzy)

    except NoAuthUserError as e:
        return {'error': str(e)}, 401  # HTTP 401 Unauthorized (authentication)
    except ScanNotFoundError as e:
        return {'error': str(e)}, 404  # HTTP 404 Not Found
    except Exception as e:
        self.logger.error(f'Error listing filesets: {str(e)}')
        return {'error': f'Error listing filesets: {str(e)}'}, 500  # HTTP 500 Internal Server Error
    else:
        return {'filesets': filesets}, 200

ScanMetadata Link

ScanMetadata(db, logger=None)

Bases: Resource

Resource class for managing scan metadata operations through REST API endpoints.

This class provides HTTP endpoints for retrieving and updating scan metadata through a RESTful interface. It handles both complete metadata operations and individual key access.

Attributes:

Name Type Description
db FSDB

The database providing the resources to serve.

logger Logger

The logger used to record operations and errors.

Initialize the resource.

Parameters:

Name Type Description Default

db Link

FSDB

A database instance providing the resources to serve.

required

logger Link

Logger

A logger instance to record operations and errors.

None
Source code in plantdb/server/api/scan.py
582
583
584
585
586
587
588
589
590
591
592
593
def __init__(self, db, logger=None):
    """Initialize the resource.

    Parameters
    ----------
    db : plantdb.commons.fsdb.core.FSDB
        A database instance providing the resources to serve.
    logger : logging.Logger
        A logger instance to record operations and errors.
    """
    self.db: FSDB = db
    self.logger: logging.Logger = logger if logger else get_logger(self.__class__.__name__)

get Link

get(scan_id, **kwargs)

Retrieve metadata for a specified scan.

This method retrieves the metadata dictionary for a scan. Optionally, it can return the value for a specific metadata key.

Parameters:

Name Type Description Default

scan_id Link

str

The ID of the scan.

required

Returns:

Type Description
Union[dict, Any]

Without a 'key' URL parameter, it returns the complete metadata dictionary. If a 'key' URL parameter is provided, it returns the value for that key.

Raises:

Type Description
ScanNotFoundError

If the specified scan doesn't exist.

KeyError

If the specified key doesn't exist in the metadata.

Notes

The method can take direct parameters in the request body with the following fields:

- key (str): If provided, returns only the value for this specific metadata key.

Examples:

>>> # Start the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> url = "http://127.0.0.1:5000" + api_endpoints.scan_metadata('real_plant')
>>> response = requests.get(url)  # Get all metadata
>>> metadata = response.json()['metadata']
>>> print(metadata['owner'])
guest
>>> response = requests.get(url+"?key=owner")  # Get a specific metadata key
>>> print(response.json()['metadata'])
guest
>>> # Stop the test server
>>> server.stop()
Source code in plantdb/server/api/scan.py
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
@sanitize_ids('scan_id')
@rate_limit(max_requests=120, window_seconds=60)
@add_jwt_from_header
@use_guest_as_default  # FIXME: Remove this if we want strict token identification
def get(self, scan_id, **kwargs):
    """Retrieve metadata for a specified scan.

    This method retrieves the metadata dictionary for a scan. Optionally, it can
    return the value for a specific metadata key.

    Parameters
    ----------
    scan_id : str
        The ID of the scan.

    Returns
    -------
    Union[dict, Any]
        Without a 'key' URL parameter, it returns the complete metadata dictionary.
        If a 'key' URL parameter is provided, it returns the value for that key.

    Raises
    ------
    plantdb.commons.fsdb.exceptions.ScanNotFoundError
        If the specified scan doesn't exist.
    KeyError
        If the specified key doesn't exist in the metadata.

    Notes
    -----
    The method can take direct parameters in the request body with the following fields:

        - key (str): If provided, returns only the value for this specific metadata key.

    Examples
    --------
    >>> # Start the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> url = "http://127.0.0.1:5000" + api_endpoints.scan_metadata('real_plant')
    >>> response = requests.get(url)  # Get all metadata
    >>> metadata = response.json()['metadata']
    >>> print(metadata['owner'])
    guest
    >>> response = requests.get(url+"?key=owner")  # Get a specific metadata key
    >>> print(response.json()['metadata'])
    guest
    >>> # Stop the test server
    >>> server.stop()
    """
    key = request.args.get('key', default=None, type=str)
    if key:
        self.logger.debug(f"Got a metadata key '{key}' for scan '{scan_id}'...")

    try:
        # Get the scan
        scan = self.db.get_scan(scan_id, **kwargs)
        # Get the metadata
        metadata = scan.get_metadata(key, default={})

    except NoAuthUserError as e:
        return {'error': str(e)}, 401  # HTTP 401 Unauthorized (authentication)
    except ScanNotFoundError as e:
        return {'error': str(e)}, 404  # HTTP 404 Not Found
    except Exception as e:
        self.logger.error(f'Error retrieving metadata: {str(e)}')
        return {'error': f'Error retrieving metadata: {str(e)}'}, 500  # HTTP 500 Internal Server Error
    else:
        return {'metadata': metadata}, 200

post Link

post(scan_id, **kwargs)

Update metadata for a specified scan.

Parameters:

Name Type Description Default

scan_id Link

str

The ID of the scan to update metadata for

required

Returns:

Type Description
dict

Response dictionary with either: - 'metadata': Updated metadata dictionary on success - 'error': Error message on failure

int

HTTP status code (200 for success, 4xx/5xx for errors)

Notes

The request body accepts a JSON object containing:

- 'metadata' (dict): the new metadata

Examples:

>>> # Start the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> # Start by log in as 'admin'
>>> user_data = {'username': 'admin', 'password': 'admin'}
>>> login_res = requests.post("http://127.0.0.1:5000" + api_endpoints.login(), json=user_data)
>>> token = login_res.json()['access_token']
>>> # Update the metadata dictionary for an existing dataset:
>>> url = "http://127.0.0.1:5000" + api_endpoints.scan_metadata("real_plant")
>>> metadata = {'object': {'description': 'Test plant scan'}}
>>> response = requests.post(url, json={'metadata': metadata}, headers={'Authorization': 'Bearer ' + token})
>>> print(response.ok)
True
>>> print(response.json()['metadata']['object']['description'])
Test plant scan
>>> _ = requests.post("http://127.0.0.1:5000" + api_endpoints.logout())  # logout
>>> # Stop the test server
>>> server.stop()
Source code in plantdb/server/api/scan.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
@sanitize_ids('scan_id')
@rate_limit(max_requests=120, window_seconds=60)
@add_jwt_from_header
def post(self, scan_id, **kwargs):
    """Update metadata for a specified scan.

    Parameters
    ----------
    scan_id : str
        The ID of the scan to update metadata for

    Returns
    -------
    dict
        Response dictionary with either:
            - 'metadata': Updated metadata dictionary on success
            - 'error': Error message on failure
    int
        HTTP status code (200 for success, 4xx/5xx for errors)

    Notes
    -----
    The request body accepts a JSON object containing:

        - 'metadata' (dict): the new metadata

    Examples
    --------
    >>> # Start the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> # Start by log in as 'admin'
    >>> user_data = {'username': 'admin', 'password': 'admin'}
    >>> login_res = requests.post("http://127.0.0.1:5000" + api_endpoints.login(), json=user_data)
    >>> token = login_res.json()['access_token']
    >>> # Update the metadata dictionary for an existing dataset:
    >>> url = "http://127.0.0.1:5000" + api_endpoints.scan_metadata("real_plant")
    >>> metadata = {'object': {'description': 'Test plant scan'}}
    >>> response = requests.post(url, json={'metadata': metadata}, headers={'Authorization': 'Bearer ' + token})
    >>> print(response.ok)
    True
    >>> print(response.json()['metadata']['object']['description'])
    Test plant scan
    >>> _ = requests.post("http://127.0.0.1:5000" + api_endpoints.logout())  # logout
    >>> # Stop the test server
    >>> server.stop()
    """
    # Get request data
    data = request.get_json()
    if not data or 'metadata' not in data:
        return {'error': 'No metadata provided in request'}, 400

    metadata = data['metadata']

    if not isinstance(metadata, dict):
        return {'error': 'Metadata must be a dictionary'}, 400

    try:
        # Get the scan
        scan = self.db.get_scan(scan_id, **kwargs)
        # Update the metadata
        scan.set_metadata(metadata, **kwargs)
        # Return updated metadata
        updated_metadata = scan.get_metadata()

    except NoAuthUserError as e:
        return {'error': str(e)}, 401  # HTTP 401 Unauthorized (authentication)
    except ScanNotFoundError as e:
        return {'error': str(e)}, 404  # HTTP 404 Not Found
    except SessionValidationError as e:
        return {'error': 'Invalid credentials'}, 401  # HTTP 401 Unauthorized (authentication)
    except Exception as e:
        self.logger.error(f'Error updating {scan_id} scan metadata: {str(e)}')
        return {'error': f'Error updating {scan_id} scan metadata: {str(e)}'}, 500  # HTTP 500 Internal Server Error
    else:
        return {'metadata': updated_metadata}, 200

ScansList Link

ScansList(db, logger=None)

Bases: Resource

A RESTful resource for managing and retrieving scan datasets.

This class implements a REST API endpoint that provides access to scan datasets. It supports filtered queries and fuzzy matching capabilities through HTTP GET requests.

Attributes:

Name Type Description
db FSDB

The database providing the resources to serve.

logger Logger

The logger used to record operations and errors.

Initialize the resource.

Parameters:

Name Type Description Default

db Link

FSDB

A database instance providing the resources to serve.

required

logger Link

Logger

A logger instance to record operations and errors.

None
Source code in plantdb/server/api/scan.py
128
129
130
131
132
133
134
135
136
137
138
139
def __init__(self, db, logger=None):
    """Initialize the resource.

    Parameters
    ----------
    db : plantdb.commons.fsdb.core.FSDB
        A database instance providing the resources to serve.
    logger : logging.Logger
        A logger instance to record operations and errors.
    """
    self.db: FSDB = db
    self.logger: logging.Logger = logger if logger else get_logger(self.__class__.__name__)

get Link

get()

Retrieve a list of scan datasets with optional filtering.

This endpoint provides access to scan datasets stored in the database. It allows filtering of results using a JSON-formatted query string and supports fuzzy matching for string-based searches.

Returns:

Type Description
list

The List of scan datasets matching the filter criteria. Each item is a dictionary containing dataset metadata.

int

HTTP status code (200 for success, 400/500 for errors).

Raises:

Type Description
HTTPException

If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client.

Notes

The method can take direct parameters in the request body with the following fields:

- filter_query (str): JSON string representing the filter query, example: ``{"object":{"species":"Arabidopsis.*"}}``.
- fuzzy (str): Boolean indicating whether to perform fuzzy filtering, ``false`` by default.

Examples:

>>> # Start the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> # Get a list of all datasets from the DB:
>>> url = "http://127.0.0.1:5000" + api_endpoints.scans()
>>> response = requests.get(url)
>>> scans_list = response.json()
>>> print(scans_list)  # List the known dataset ids
['arabidopsis000', 'virtual_plant_analyzed', 'real_plant_analyzed', 'real_plant', 'virtual_plant']
>>> # Get the metadata dictionary for these scans:
>>> def get_md(scan_id): return requests.get("http://127.0.0.1:5000" + api_endpoints.scan_metadata(scan_id))
>>> md_dict = {}
>>> for scan_id in scans_list: md_dict[scan_id]=get_md(scan_id).json()['metadata']
>>> for scan_id, md in md_dict.items(): print(f"{scan_id}: {md.get('object', {}).get('environment')}")
>>> # Get a list of datasets with fuzzy filtering on metadata
>>> query = {"object": {"environment": "Lyon indoor"}}
>>> response = requests.get(url, json={"filterQuery": query}, params={"fuzzy": "true"})
>>> filtered_scans = response.json()
>>> print(filtered_scans)  # list of scan IDs matching the filter
['real_plant_analyzed', 'real_plant']
>>> # Stop the test server
>>> server.stop()
Source code in plantdb/server/api/scan.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
@rate_limit(max_requests=30, window_seconds=60)
def get(self):
    """Retrieve a list of scan datasets with optional filtering.

    This endpoint provides access to scan datasets stored in the database. It allows
    filtering of results using a JSON-formatted query string and supports fuzzy
    matching for string-based searches.

    Returns
    -------
    list
        The List of scan datasets matching the filter criteria.
        Each item is a dictionary containing dataset metadata.
    int
        HTTP status code (``200`` for success, ``400``/``500`` for errors).

    Raises
    ------
    http.client.HTTPException
         If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client.

    Notes
    -----
    The method can take direct parameters in the request body with the following fields:

        - filter_query (str): JSON string representing the filter query, example: ``{"object":{"species":"Arabidopsis.*"}}``.
        - fuzzy (str): Boolean indicating whether to perform fuzzy filtering, ``false`` by default.

    Examples
    --------
    >>> # Start the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> # Get a list of all datasets from the DB:
    >>> url = "http://127.0.0.1:5000" + api_endpoints.scans()
    >>> response = requests.get(url)
    >>> scans_list = response.json()
    >>> print(scans_list)  # List the known dataset ids
    ['arabidopsis000', 'virtual_plant_analyzed', 'real_plant_analyzed', 'real_plant', 'virtual_plant']
    >>> # Get the metadata dictionary for these scans:
    >>> def get_md(scan_id): return requests.get("http://127.0.0.1:5000" + api_endpoints.scan_metadata(scan_id))
    >>> md_dict = {}
    >>> for scan_id in scans_list: md_dict[scan_id]=get_md(scan_id).json()['metadata']
    >>> for scan_id, md in md_dict.items(): print(f"{scan_id}: {md.get('object', {}).get('environment')}")
    >>> # Get a list of datasets with fuzzy filtering on metadata
    >>> query = {"object": {"environment": "Lyon indoor"}}
    >>> response = requests.get(url, json={"filterQuery": query}, params={"fuzzy": "true"})
    >>> filtered_scans = response.json()
    >>> print(filtered_scans)  # list of scan IDs matching the filter
    ['real_plant_analyzed', 'real_plant']
    >>> # Stop the test server
    >>> server.stop()
    """
    # Get fuzzy parameter from request URL
    fuzzy = request.args.get('fuzzy', False, type=bool)
    timelapse_id = request.args.get('timelapse_id', None)
    sort = request.args.get('sort', None)
    # Get filter query from "filterQuery" JSON data
    query_data = request.get_json(silent=True)
    if isinstance(query_data, dict):
        query = query_data.get("filterQuery")
    else:
        query = None

    if timelapse_id is not None:
        if query is None:
            query = {"timelapse": {"id": timelapse_id}}
        elif isinstance(query, dict):
            tl_query = query.setdefault("timelapse", {})
            if isinstance(tl_query, dict):
                tl_query["id"] = timelapse_id

    try:
        # Query database for matching scans, allowing access to all owners
        scans_list = self.db.list_scans(query=query, fuzzy=fuzzy, owner_only=False, sort=sort)
    except Exception as e:
        # Return an error response if any exception occurs
        return {'error': f'Error retrieving scan list: {str(e)}'}, 500  # HTTP 500 Internal Server Error
    else:
        return scans_list, 200

ScansTable Link

ScansTable(db, logger=None, deploy_prefix='')

Bases: Resource

A RESTful resource for managing and retrieving scan dataset information.

This class provides a REST API endpoint to serve information about scan datasets. It supports filtering datasets based on query parameters and returns detailed information about each matching scan.

Attributes:

Name Type Description
db FSDB

The database providing the resources to serve.

logger Logger

The logger instance for this resource.

See Also

plantdb.server.services.scan.get_scan_info : Function used to extract information for each scan

Initialize the resource.

Parameters:

Name Type Description Default

db Link

FSDB

A database instance providing the resources to serve.

required

logger Link

Logger

A logger instance to record operations and errors.

None

deploy_prefix Link

str

Deployment (reverse-proxy) prefix prepended before /api/v1/... when generating endpoint URLs in scan responses.

''
Source code in plantdb/server/api/scan.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def __init__(self, db, logger=None, deploy_prefix=""):
    """Initialize the resource.

    Parameters
    ----------
    db : plantdb.commons.fsdb.core.FSDB
        A database instance providing the resources to serve.
    logger : logging.Logger
        A logger instance to record operations and errors.
    deploy_prefix : str, optional
        Deployment (reverse-proxy) prefix prepended before ``/api/v1/...``
        when generating endpoint URLs in scan responses.
    """
    self.db: FSDB = db
    self.logger: logging.Logger = logger if logger else get_logger(self.__class__.__name__)
    self.deploy_prefix: str = deploy_prefix

get Link

get(**kwargs)

Retrieve a list of scan dataset information.

This method handles GET requests to retrieve scan information. It supports filtering through query parameters and returns detailed information about matching scans.

Returns:

Type Description
List[Dict]

List of dictionaries containing scan information with:

- metadata (dict): Scan metadata including acquisition date, object info
- tasks (dict): Information about processing tasks
- files (dict): File paths and URIs related to the scan

Raises:

Type Description
JSONDecodeError

If the provided filterQuery parameter is not valid JSON.

HTTPException

If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client.

Notes

The method can take direct parameters in the request body with the following fields:

- filter_query: JSON string representing the filter query, example: ``{"object":{"species":"Arabidopsis.*"}}``.
- fuzzy: Boolean indicating whether to perform fuzzy filtering, ``False`` by default.

Examples:

>>> # Start the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> # Get a list of information dictionaries about all datasets:
>>> url = "http://127.0.0.1:5000" + api_endpoints.scans_info()
>>> response = requests.get(url)
>>> scans_info = response.json()
>>> # List the known dataset id:
>>> print(sorted(scan['id'] for scan in scans_info))
['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
>>> # Add a metadata filter to the query:
>>> query = {"object": {"environment": "Lyon indoor"}}
>>> response = requests.get(url, json={"filterQuery": query}, params={"fuzzy": "true"})
>>> scans_info = response.json()
>>> print(sorted(scan['id'] for scan in scans_info))
['real_plant', 'real_plant_analyzed']
Source code in plantdb/server/api/scan.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
@rate_limit(max_requests=120, window_seconds=60)
@add_jwt_from_header
@use_guest_as_default  # FIXME: Remove this if we want strict token identification
def get(self, **kwargs):
    """Retrieve a list of scan dataset information.

    This method handles GET requests to retrieve scan information. It supports
    filtering through query parameters and returns detailed information about
    matching scans.

    Returns
    -------
    List[Dict]
        List of dictionaries containing scan information with:

            - metadata (dict): Scan metadata including acquisition date, object info
            - tasks (dict): Information about processing tasks
            - files (dict): File paths and URIs related to the scan

    Raises
    ------
    JSONDecodeError
        If the provided filterQuery parameter is not valid JSON.
    http.client.HTTPException
         If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client.

    Notes
    -----
    The method can take direct parameters in the request body with the following fields:

        - filter_query: JSON string representing the filter query, example: ``{"object":{"species":"Arabidopsis.*"}}``.
        - fuzzy: Boolean indicating whether to perform fuzzy filtering, ``False`` by default.

    Examples
    --------
    >>> # Start the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> # Get a list of information dictionaries about all datasets:
    >>> url = "http://127.0.0.1:5000" + api_endpoints.scans_info()
    >>> response = requests.get(url)
    >>> scans_info = response.json()
    >>> # List the known dataset id:
    >>> print(sorted(scan['id'] for scan in scans_info))
    ['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
    >>> # Add a metadata filter to the query:
    >>> query = {"object": {"environment": "Lyon indoor"}}
    >>> response = requests.get(url, json={"filterQuery": query}, params={"fuzzy": "true"})
    >>> scans_info = response.json()
    >>> print(sorted(scan['id'] for scan in scans_info))
    ['real_plant', 'real_plant_analyzed']
    """
    # Get fuzzy parameter from request URL
    fuzzy = request.args.get('fuzzy', False, type=bool)
    timelapse_id = request.args.get('timelapse_id', None)
    sort = request.args.get('sort', None)
    # Get filter query from "filterQuery" JSON data
    query_data = request.get_json(silent=True)
    if isinstance(query_data, dict):
        query = query_data.get("filterQuery")
    else:
        query = None

    if timelapse_id is not None:
        if query is None:
            query = {"timelapse": {"id": timelapse_id}}
        elif isinstance(query, dict):
            tl_query = query.setdefault("timelapse", {})
            if isinstance(tl_query, dict):
                tl_query["id"] = timelapse_id

    try:
        # Query database for matching scans, allowing access to all owners
        scans_list = self.db.list_scans(query=query, fuzzy=fuzzy, owner_only=False, sort=sort)
    except Exception as e:
        # Return an error response if any exception occurs
        return {'error': f'Error retrieving scan list: {str(e)}'}, 500  # HTTP 500 Internal Server Error

    scans_info = []
    for scan_id in scans_list:
        try:
            scan = self.db.get_scan(scan_id, **kwargs)
            scan_info = get_scan_info(scan, logger=self.logger, prefix=self.deploy_prefix, **kwargs)
        except NoAuthUserError as e:
            return {'error': str(e)}, 401  # HTTP 401 Unauthorized (authentication)
        except ScanNotFoundError as e:
            return {'error': str(e)}, 404  # HTTP 404 Not Found
        except Exception as e:
            return {'error': f"Error while accessing '{scan_id}': {str(e)}"}, 404  # HTTP 404 Not Found
        else:
            scans_info.append(scan_info)
    return scans_info, 200