API Endpoints

This section documents all available API endpoints for interacting with DataMint resources.

Projects API

class datamint.api.endpoints.projects_api.ProjectsApi(config, client=None, resources_api=None)

Bases: CRUDEntityApi[Project]

API handler for project-related endpoints.

Parameters:
add_resources(resources, project)

Add resources to a project.

Parameters:
  • resources (str | Sequence[str] | Resource | Sequence[Resource]) – The resource unique id or a list of resource unique ids.

  • project (str | Project) – The project name, id or Project object to add the resource to.

Return type:

None

create(name, description, resources_ids=None, is_active_learning=False, two_up_display=False)

Create a new project.

Parameters:
  • name (str) – The name of the project.

  • description (str) – The description of the project.

  • resources_ids (list[str] | None) – The list of resource ids to be included in the project.

  • is_active_learning (bool) – Whether the project is an active learning project or not.

  • two_up_display (bool) – Allow annotators to display multiple resources for annotation.

Return type:

str

Returns:

The id of the created project.

get_all(limit=None)

Get all projects.

Parameters:

limit (int | None) – The maximum number of projects to return. If None, return all projects.

Return type:

Sequence[Project]

Returns:

A list of project instances.

get_by_name(name, include_archived=True)

Get a project by its name.

Parameters:
  • name (str) – The name of the project.

  • include_archived (bool) – Whether to include archived projects in the search.

Return type:

Project | None

Returns:

The project instance if found, otherwise None.

get_project_resources(project)

Get resources associated with a specific project.

Parameters:

project (Project | str) – The ID or instance of the project to fetch resources for.

Return type:

list[Resource]

Returns:

A list of resource instances associated with the project.

set_work_status(project, resource, status)

Set the status of a resource.

Parameters:
  • project (str | Project) – The project unique id or a project object.

  • resource (str | Resource) – The resource unique id or a resource object.

  • status (Literal['opened', 'annotated', 'closed']) – The new status to set.

Return type:

None

Resources API

datamint.api.endpoints.resources_api.ResourceFields

The available fields to order resources. Possible values: ‘modality’, ‘created_by’, ‘published_by’, ‘published_on’, ‘filename’, ‘created_at’ (default).

Type:

TypeAlias

alias of Literal[‘modality’, ‘created_by’, ‘published_by’, ‘published_on’, ‘filename’, ‘created_at’]

datamint.api.endpoints.resources_api.ResourceStatus

The available resource status. Possible values: ‘new’, ‘inbox’, ‘published’, ‘archived’.

Type:

TypeAlias

alias of Literal[‘new’, ‘inbox’, ‘published’, ‘archived’]

class datamint.api.endpoints.resources_api.ResourcesApi(config, client=None, annotations_api=None, projects_api=None)

Bases: CreatableEntityApi[Resource], DeletableEntityApi[Resource]

API handler for resource-related endpoints.

Parameters:
add_tags(resource, tags)

Add tags to a resource, IMPORTANT: This appends to existing tags. :type resource: str | Resource :param resource: The resource unique id or Resource object. :type tags: Sequence[str] :param tags: The tags to add.

bulk_delete(entities)

Delete multiple entities. Faster than deleting them one by one.

Parameters:

entities (Sequence[str | Resource]) – Sequence of unique identifiers for the entities to delete or the entity instances themselves.

Raises:

httpx.HTTPStatusError – If deletion fails or any entity not found

Return type:

None

download_multiple_resources(resources, save_path, add_extension=False, overwrite=True)

Download multiple resources and save them to the specified paths. This is faster than downloading them one by one.

Parameters:
  • resources (Sequence[str] | Sequence[Resource]) – A list of resource unique ids.

  • save_path (Sequence[str] | str) – A list of paths to save the files or a directory path, of same length as resources. If a directory path is provided, files will be saved in that directory.

  • add_extension (bool) – Whether to add the appropriate file extension to the save_path based on the content type.

  • overwrite (bool)

Returns:

A list of paths where the files were saved. Important if add_extension=True.

Return type:

list[str]

download_resource_file(resource, save_path=None, auto_convert=True, add_extension=False)

Download a resource file.

Parameters:
  • resource (str | Resource) – The resource unique id or Resource instance.

  • save_path (str | None) – The path to save the file.

  • auto_convert (bool) – Whether to convert the file to a known format or not.

  • add_extension (bool) – Whether to add the appropriate file extension to the save_path based on the content type.

Return type:

pydicom.dataset.Dataset | Image.Image | cv2.VideoCapture | nib_FileBasedImage | tuple[pydicom.dataset.Dataset | Image.Image | cv2.VideoCapture | nib_FileBasedImage, str] | bytes

Returns:

The resource content in bytes (if auto_convert=False) or the resource object (if auto_convert=True). if add_extension=True, the function will return a tuple of (resource_data, save_path).

Raises:

ResourceNotFoundError – If the resource does not exists.

Example

>>> api_handler.download_resource_file('resource_id', auto_convert=False)
    returns the resource content in bytes.
>>> api_handler.download_resource_file('resource_id', auto_convert=True)
    Assuming this resource is a dicom file, it will return a pydicom.Dataset object.
>>> api_handler.download_resource_file('resource_id', save_path='path/to/dicomfile.dcm')
    saves the file in the specified path.
download_resource_frame(resource, frame_index)

Download a frame of a resource. This is faster than downloading the whole resource and then extracting the frame.

Parameters:
  • resource (str | Resource) – The resource unique id or Resource object.

  • frame_index (int) – The index of the frame to download.

Returns:

The frame as a PIL image.

Return type:

Image.Image

Raises:
get_annotations(resource)

Get annotations for a specific resource.

Parameters:

resource (str | Resource) – The resource ID or Resource instance to fetch annotations for.

Return type:

Sequence[Annotation]

Returns:

A sequence of Annotation objects associated with the specified resource.

get_list(status=None, from_date=None, to_date=None, tags=None, modality=None, mimetype=None, order_field=None, order_ascending=None, channel=None, project_name=None, filename=None, limit=None)

Get resources with optional filtering.

Parameters:
  • status (Literal['new', 'inbox', 'published', 'archived'] | None) – The resource status. Possible values: ‘inbox’, ‘published’, ‘archived’ or None. If None, it will return all resources.

  • from_date (date | str | None) – The start date (inclusive).

  • to_date (date | str | None) – The end date (exclusive).

  • tags (Sequence[str] | None) – The tags to filter the resources.

  • modality (str | None) – The modality of the resources.

  • mimetype (str | None) – The mimetype of the resources.

  • order_field (Literal['modality', 'created_by', 'published_by', 'published_on', 'filename', 'created_at'] | None) – The field to order the resources. See ResourceFields.

  • order_ascending (bool | None) – Whether to order the resources in ascending order.

  • project_name (str | list[str] | None) – The project name or a list of project names to filter resources by project. If multiple projects are provided, resources will be filtered to include only those belonging to ALL of the specified projects.

  • channel (str | None)

  • filename (str | None)

  • limit (int | None)

Return type:

Sequence[Resource]

publish_resources(resources)

Publish resources, changing their status to ‘published’.

Parameters:

resources (str | Resource | Sequence[str | Resource]) – The resources to publish. Can be a Resource object (instead of a list)

Raises:

ResourceNotFoundError – If the resource does not exists or the project does not exists.

Return type:

None

set_tags(resource, tags)

Set tags for a resource, IMPORTANT: This replaces all existing tags. :type resource: str | Resource :param resource: The resource unique id or Resource object. :type tags: Sequence[str] :param tags: The tags to set.

upload_resource(file_path, mimetype=None, anonymize=False, anonymize_retain_codes=[], tags=None, mung_filename=None, channel=None, publish=False, publish_to=None, segmentation_files=None, transpose_segmentation=False, modality=None, metadata=None, discard_dicom_reports=True)

Upload a single resource.

This is a convenience method that wraps upload_resources for single file uploads. It provides a cleaner interface when uploading just one file.

Parameters:
  • file_path (str | IO | Dataset) – The path to the resource file or IO object.

  • mimetype (str | None) – The mimetype of the resource. If None, it will be guessed.

  • anonymize (bool) – Whether to anonymize the DICOM or not.

  • anonymize_retain_codes (Sequence[tuple]) – The tags to retain when anonymizing the DICOM.

  • tags (Sequence[str] | None) – The tags to add to the resource.

  • mung_filename (Sequence[int] | Literal['all'] | None) – The parts of the filepath to keep when renaming the resource file. ‘all’ keeps all parts.

  • channel (str | None) – The channel to upload the resource to. An arbitrary name to group the resources.

  • publish (bool) – Whether to directly publish the resource or not. It will have the ‘published’ status.

  • publish_to (str | None) – The project name or id to publish the resource to. It will have the ‘published’ status and will be added to the project. If this is set, publish parameter is ignored.

  • segmentation_files (dict | None) – The segmentation files to upload. Should be a dict with: - ‘files’: A list of paths to the segmentation files. Example: [‘seg1.nii.gz’, ‘seg2.nii.gz’]. - ‘names’: A dict mapping pixel values to class names. Example: {1: ‘Brain’, 2: ‘Lung’}.

  • transpose_segmentation (bool) – Whether to transpose the segmentation files or not.

  • modality (str | None) – The modality of the resource.

  • metadata (dict | str | None) – JSON metadata to include with the resource. Can be a file path (str) or already loaded dictionary (dict).

  • discard_dicom_reports (bool) – Whether to discard DICOM reports or not.

Returns:

The resource ID of the uploaded resource.

Return type:

str

Raises:

Example

# Simple upload
resource_id = api.resources.upload_resource('path/to/file.dcm')

# Upload with metadata and segmentation
resource_id = api.resources.upload_resource(
    'path/to/file.dcm',
    tags=['tutorial', 'case1'],
    channel='study_channel',
    segmentation_files={
        'files': ['path/to/segmentation.nii.gz'],
        'names': {1: 'Brain', 2: 'Lung'}
    },
    metadata={'patient_age': 45, 'modality': 'CT'}
)
upload_resources(files_path, mimetype=None, anonymize=False, anonymize_retain_codes=[], on_error='raise', tags=None, mung_filename=None, channel=None, publish=False, publish_to=None, segmentation_files=None, transpose_segmentation=False, modality=None, assemble_dicoms=True, metadata=None, discard_dicom_reports=True, progress_bar=False)

Upload multiple resources.

Note: For uploading a single resource, use upload_resource() instead.

Parameters:
  • files_path (Sequence[str | IO | Dataset]) – A sequence of paths to resource files, IO objects, or pydicom.Dataset objects. Must contain at least 2 items. Supports mixed types within the sequence.

  • mimetype (str) – The mimetype of the resources. If None, it will be guessed.

  • anonymize (bool) – Whether to anonymize the dicoms or not.

  • anonymize_retain_codes (Sequence[tuple]) – The tags to retain when anonymizing the dicoms.

  • on_error (Literal['raise', 'skip']) – Whether to raise an exception when an error occurs or to skip the error.

  • tags (Optional[Sequence[str]]) – The tags to add to the resources.

  • mung_filename (Sequence[int] | Literal['all']) – The parts of the filepath to keep when renaming the resource file. ‘’all’’ keeps all parts.

  • channel (Optional[str]) – The channel to upload the resources to. An arbitrary name to group the resources.

  • publish (bool) – Whether to directly publish the resources or not. They will have the ‘published’ status.

  • publish_to (Optional[str]) – The project name or id to publish the resources to. They will have the ‘published’ status and will be added to the project. If this is set, publish parameter is ignored.

  • segmentation_files (Optional[list[Union[list[str], dict]]]) –

    The segmentation files to upload. If each element is a dict, it should have two keys: ‘files’ and ‘names’.

    • files: A list of paths to the segmentation files. Example: [‘seg1.nii.gz’, ‘seg2.nii.gz’].

    • names: Can be a list (same size of files) of labels for the segmentation files. Example: [‘Brain’, ‘Lung’].

  • transpose_segmentation (bool) – Whether to transpose the segmentation files or not.

  • modality (Optional[str]) – The modality of the resources.

  • assemble_dicoms (bool) – Whether to assemble the dicom files or not based on the SeriesInstanceUID and InstanceNumber attributes.

  • metadata (Optional[list[str | dict | None]]) – JSON metadata to include with each resource. Must have the same length as files_path. Can be file paths (str) or already loaded dictionaries (dict).

  • discard_dicom_reports (bool)

  • progress_bar (bool)

Raises:
  • ValueError – If a single resource is provided instead of multiple resources.

  • ResourceNotFoundError – If publish_to is supplied, and the project does not exists.

Returns:

A list of resource IDs or errors.

Return type:

list[str | Exception]

Annotations API

class datamint.api.endpoints.annotations_api.AnnotationsApi(config, client=None, models_api=None, resources_api=None)

Bases: CreatableEntityApi[Annotation], DeletableEntityApi[Annotation]

API handler for annotation-related endpoints.

Parameters:
add_line_annotation(point1, point2, resource_id, identifier, frame_index=None, dicom_metadata=None, coords_system='pixel', project=None, worklist_id=None, imported_from=None, author_email=None, model_id=None)

Add a line annotation to a resource.

Parameters:
  • point1 (tuple[int, int] | tuple[float, float, float]) – The first point of the line. Can be a 2d or 3d point. If coords_system is ‘pixel’, it must be a 2d point and it represents the pixel coordinates of the image. If coords_system is ‘patient’, it must be a 3d point and it represents the patient coordinates of the image, relative to the DICOM metadata.

  • 'patient' (If coords_system is)

  • point. (it must be a 3d)

  • point2 (tuple[int, int] | tuple[float, float, float]) – The second point of the line. See point1 for more details.

  • resource_id (str) – The resource unique id.

  • identifier (str) – The annotation identifier, also as known as the annotation’s label.

  • frame_index (int | None) – The frame index of the annotation.

  • dicom_metadata (Dataset | str | None) – The DICOM metadata of the image. If provided, the coordinates will be converted to the correct coordinates automatically using the DICOM metadata.

  • coords_system (Literal['pixel', 'patient']) – The coordinate system of the points. Can be ‘pixel’, or ‘patient’. If ‘pixel’, the points are in pixel coordinates. If ‘patient’, the points are in patient coordinates (see DICOM patient coordinates).

  • project (str | None) – The project unique id or name.

  • worklist_id (str | None) – The annotation worklist unique id. Optional.

  • imported_from (str | None) – The imported from source value.

  • author_email (str | None) – The email to consider as the author of the annotation. If None, use the customer of the api key.

  • model_id (str | None) – The model unique id. Optional.

Return type:

Sequence[str]

Example

res_id = 'aa93813c-cef0-4edd-a45c-85d4a8f1ad0d'
api.add_line_annotation([0, 0], (10, 30),
                        resource_id=res_id,
                        identifier='Line1',
                        frame_index=2,
                        project='Example Project')
bulk_download_file(annotations, save_paths)

Alias for download_multiple_files()

Parameters:
  • annotations (Sequence[str | Annotation])

  • save_paths (Sequence[str | Path] | str)

Return type:

None

create(resource, annotation_dto)

Create a new annotation.

Parameters:
Return type:

str | Sequence[str]

Returns:

The id of the created annotation or a list of ids if multiple annotations were created.

create_image_classification(resource, identifier, value, imported_from=None, model_id=None)

Create an image-level classification annotation.

Parameters:
  • resource (str | Resource) – The resource unique id or Resource instance.

  • identifier (str) – The annotation identifier/label.

  • value (str) – The classification value.

  • imported_from (str | None) – The imported from source value.

  • model_id (str | None) – The model unique id.

Return type:

str

Returns:

The id of the created annotation.

download_file(annotation, fpath_out=None)

Download the segmentation file for a given resource and annotation.

Parameters:
  • annotation (str | Annotation) – The annotation unique id or an annotation object.

  • fpath_out (str | PathLike | None) – (Optional) The file path to save the downloaded segmentation file.

Returns:

The content of the downloaded segmentation file in bytes format.

Return type:

bytes

download_multiple_files(annotations, save_paths)

Download multiple segmentation files and save them to the specified paths.

Parameters:
  • annotations (Sequence[str | Annotation]) – A list of annotation unique ids or annotation objects.

  • save_paths (Sequence[str | Path] | str) – A list of paths to save the files or a directory path.

Return type:

None

get_list(resource=None, annotation_type=None, annotator_email=None, date_from=None, date_to=None, dataset_id=None, worklist_id=None, status=None, load_ai_segmentations=None, limit=None)

Get entities with optional filtering.

Return type:

Sequence[Annotation]

Returns:

List of entity instances.

Raises:

httpx.HTTPStatusError – If the request fails.

Parameters:
  • resource (str | Resource | None)

  • annotation_type (AnnotationType | str | None)

  • annotator_email (str | None)

  • date_from (date | None)

  • date_to (date | None)

  • dataset_id (str | None)

  • worklist_id (str | None)

  • status (Literal['new', 'published'] | None)

  • load_ai_segmentations (bool | None)

  • limit (int | None)

patch(annotation, identifier)

Update the project assignment for an annotation.

Parameters:
  • annotation (str | Annotation) – The annotation unique id or Annotation instance.

  • identifier (str) – The new identifier/label for the annotation.

Raises:

DatamintException – If the update fails.

Return type:

None

static standardize_segmentation_names(name)

Standardize segmentation names to a consistent format.

Parameters:

name (str | dict | None) – The name input in various formats.

Return type:

dict

Returns:

Standardized name dictionary.

upload_annotation_file(resource, annotation_id, file, content_type=None, filename=None)

Upload a file for an existing annotation.

Parameters:
  • resource (str | Resource) – The resource unique id or Resource instance.

  • annotation_id (str) – The annotation unique id.

  • file (str | IO) – Path to the file or a file-like object.

  • content_type (str | None) – The MIME type of the file.

  • filename (str | None) – Optional filename to use in the upload. If None and file is a path, the basename of the path will be used.

Raises:

DatamintException – If the upload fails.

async upload_annotation_file_async(resource, annotation_id, file, content_type=None, filename=None)

Upload a file for an existing annotation asynchronously.

Parameters:
  • resource (str | Resource) – The resource unique id or Resource instance.

  • annotation_id (str) – The annotation unique id.

  • file (str | IO) – Path to the file or a file-like object.

  • content_type (str | None) – The MIME type of the file.

  • filename (str | None) – Optional filename to use in the upload. If None and file is a path, the basename of the path will be used.

Raises:

DatamintException – If the upload fails.

Example

await ann_api.upload_annotation_file_async(
    resource='your_resource_id',
    annotation_id='your_annotation_id',
    file='path/to/your/file.png',
    content_type='image/png',
    filename='custom_name.png'
)
upload_segmentations(resource, file_path, name=None, frame_index=None, imported_from=None, author_email=None, discard_empty_segmentations=True, worklist_id=None, model_id=None, transpose_segmentation=False, ai_model_name=None)

Upload segmentations to a resource.

Parameters:
  • resource (str | Resource) – The resource unique ID or Resource instance.

  • file_path (str | ndarray) – The path to the segmentation file or a numpy array. If a numpy array is provided, it can have the shape: - (height, width, #frames) or (height, width) for grayscale segmentations - (3, height, width, #frames) for RGB segmentations For NIfTI files (.nii/.nii.gz), the entire volume is uploaded as a single segmentation.

  • name (str | dict[int, str] | dict[tuple, str] | None) – The name of the segmentation. Can be: - str: Single name for all segmentations - dict[int, str]: Mapping pixel values to names for grayscale segmentations - dict[tuple[int, int, int], str]: Mapping RGB tuples to names for RGB segmentations Use ‘default’ as a key for a unnamed classes. Example: {(255, 0, 0): ‘Red_Region’, (0, 255, 0): ‘Green_Region’}

  • frame_index (int | list[int] | None) – The frame index of the segmentation. If a list, it must have the same length as the number of frames in the segmentation. If None, it is assumed that the segmentations are in sequential order starting from 0. This parameter is ignored for NIfTI files as they are treated as volume segmentations.

  • imported_from (str | None) – The imported from value.

  • author_email (str | None) – The author email.

  • discard_empty_segmentations (bool) – Whether to discard empty segmentations or not.

  • worklist_id (str | None) – The annotation worklist unique id.

  • model_id (str | None) – The model unique id.

  • transpose_segmentation (bool) – Whether to transpose the segmentation or not.

  • ai_model_name (str | None) – Optional AI model name to associate with the segmentation.

Return type:

list[str]

Returns:

List of segmentation unique ids.

Raises:
  • ResourceNotFoundError – If the resource does not exist or the segmentation is invalid.

  • FileNotFoundError – If the file path does not exist.

  • ValueError – If frame_index is provided for NIfTI files or invalid parameters.

Example

# Grayscale segmentation
api.annotations.upload_segmentations(resource_id, 'path/to/segmentation.png', 'SegmentationName')

# RGB segmentation with numpy array
seg_data = np.random.randint(0, 3, size=(3, 2140, 1760, 1), dtype=np.uint8)
rgb_names = {(1, 0, 0): 'Red_Region', (0, 1, 0): 'Green_Region', (0, 0, 1): 'Blue_Region'}
api.annotations.upload_segmentations(resource_id, seg_data, rgb_names)

# Volume segmentation
api.annotations.upload_segmentations(resource_id, 'path/to/segmentation.nii.gz', 'VolumeSegmentation')

Channels API

Channels API endpoint for managing channel resources.

This module provides functionality to interact with channels, which are collections of resources grouped together for batch processing or organization purposes.

class datamint.api.endpoints.channels_api.ChannelsApi(config, client=None)

Bases: EntityBaseApi[Channel]

API client for channel-related operations.

Parameters:

client (Client | None)

Users API

class datamint.api.endpoints.users_api.UsersApi(config, client=None)

Bases: CreatableEntityApi[User]

Parameters:
create(email, password=None, firstname=None, lastname=None, roles=None)

Create a new user.

Parameters:
  • email (str) – The user’s email address.

  • password (str | None) – The user’s password. If None, a random password will be generated.

  • firstname (str | None) – The user’s first name.

  • lastname (str | None) – The user’s last name.

  • roles (list[str] | None) – List of roles to assign to the user.

Return type:

str

Returns:

The id of the created user.