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_headerdecorator 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 |
|---|---|---|---|
|
FSDB
|
A database instance providing the resources to serve. |
required |
|
Logger
|
A logger instance to record operations and errors. |
None
|
|
str
|
Deployment (reverse-proxy) prefix prepended before |
''
|
Source code in plantdb/server/api/scan.py
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 | |
get
Link
get(scan_id, **kwargs)
Retrieve detailed information about a specific scan dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
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: |
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 | |
post
Link
post(scan_id, **kwargs)
Create a new scan dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
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: |
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 | |
ScanFilesets
Link
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 |
|---|---|---|---|
|
FSDB
|
A database instance providing the resources to serve. |
required |
|
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 | |
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 |
|---|---|---|---|
|
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 | |
ScanMetadata
Link
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 |
|---|---|---|---|
|
FSDB
|
A database instance providing the resources to serve. |
required |
|
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 | |
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 |
|---|---|---|---|
|
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 | |
post
Link
post(scan_id, **kwargs)
Update metadata for a specified scan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
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 | |
ScansList
Link
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 |
|---|---|---|---|
|
FSDB
|
A database instance providing the resources to serve. |
required |
|
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 | |
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 ( |
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 | |
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 |
|---|---|---|---|
|
FSDB
|
A database instance providing the resources to serve. |
required |
|
Logger
|
A logger instance to record operations and errors. |
None
|
|
str
|
Deployment (reverse-proxy) prefix prepended before |
''
|
Source code in plantdb/server/api/scan.py
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | |
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: |
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 | |