Skip to content

Privileged API Reference

Warning

Classes on this page target privileged endpoints and require valid NMDCAuth credentials. They are intended for authorized users who need metadata submission, identifier minting, or staging workflows.

Authentication Support

NMDCAuth is required for all privileged classes on this page.

NMDCAuth

NMDCAuth(client_id: str | None = None, client_secret: str | None = None, username: str | None = None, password: str | None = None, api_base_url: str = 'https://api.microbiomedata.org', env: str = '')

Bases: nmdc_client.api_client.NMDCAPIClient

Authentication handler for NMDC API operations.

Parameters:

Name Type Description Default
client_id str | None

The client ID for NMDC API authentication. See Notes for further details.

None
client_secret str | None

The client secret for NMDC API authentication. See Notes for further details.

None
username str | None

The username for NMDC API authentication. See Notes for further details.

None
password str | None

The password for NMDC API authentication. See Notes for further details.

None
api_base_url str

The base URL of an instance of the NMDC Runtime API. By default, this is the base URL of the production instance.

'https://api.microbiomedata.org'
env str

Deprecated. Use api_base_url instead. Previously used to specify the API environment (e.g., "prod", "dev").

''
Notes

Security Warning - your credentials should be stored in a secure location. Do not hard-code these values in your code; we recommend using environment variables.

You must provide either:

  • client_id and client_secret (for client credentials grant), OR
  • username and password (for password grant).
Warnings

The env parameter is deprecated. Use api_base_url instead.

Source code in nmdc_client/auth.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def __init__(
    self,
    client_id: str | None = None,
    client_secret: str | None = None,
    username: str | None = None,
    password: str | None = None,
    api_base_url: str = API_BASE_URL,
    env: str = "",
):
    super().__init__(
        api_base_url=api_base_url,
        env=env,
    )
    self.client_id = client_id
    self.client_secret = client_secret
    self.username = username
    self.password = password
    self._token: str | None = None
    self._token_expires_at: datetime | None = None
    self._oauth_session: Any | None = None
    self.grant_type: str | None = (
        "client_credentials"
        if (self.client_id and self.client_secret)
        else "password"
        if (self.username and self.password)
        else None
    )

get_token

get_token() -> str

Get a valid access token, refreshing if necessary.

Source code in nmdc_client/auth.py
86
87
88
89
90
91
def get_token(self) -> str:
    """Get a valid access token, refreshing if necessary."""
    if self._is_token_valid():
        assert isinstance(self._token, str)  # to appease mypy
        return self._token
    return self._refresh_token()

has_credentials

has_credentials() -> bool

Check if the credentials are passed in properly.

Source code in nmdc_client/auth.py
78
79
80
81
82
83
84
def has_credentials(self) -> bool:
    """Check if the credentials are passed in properly."""
    if self.client_id and self.client_secret:
        return True
    elif self.username and self.password:
        return True
    return False

Authentication Requirement

Instantiate NMDCAuth and pass it to privileged classes:

from nmdc_client.auth import NMDCAuth
from nmdc_client.metadata import Metadata

auth = NMDCAuth(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET")
metadata_client = Metadata(auth=auth)

Metadata Submission

Metadata

Metadata(api_base_url: str = 'https://api.microbiomedata.org', auth: NMDCAuth | None = None, env: str = '')

Bases: nmdc_client.api_client.NMDCAPIClient

Class to interact with the NMDC API metadata endpoints.

This class includes methods for interacting with endpoints for metadata management, including validation and submission. It is not intended for general/public use.

Parameters:

Name Type Description Default
api_base_url str

The base URL of the NMDC API.

'https://api.microbiomedata.org'
auth NMDCAuth | None

An instance of the NMDCAuth class for authentication.

None
Warnings

The env parameter is deprecated. Use api_base_url instead.

Source code in nmdc_client/metadata.py
31
32
33
34
35
36
37
38
39
40
41
def __init__(
    self,
    api_base_url: str = API_BASE_URL,
    auth: NMDCAuth | None = None,
    env: str = "",
):
    super().__init__(
        api_base_url=api_base_url,
        env=env,
    )
    self.auth = auth or NMDCAuth(api_base_url=self.api_base_url)

submit_json

submit_json(json_records: list[dict] | str) -> int

Submits a json file to the NMDC metadata database via the NMDC Runtime API's json_submit endpoint.

Parameters:

Name Type Description Default
json_records list[dict] | str

The json records to be submitted. Can be passed in as a file path or list of dictionaries.

required

Returns:

Type Description
int

The HTTP status code of the submission request.

Raises:

Type Description
Exception

If the submission fails.

Source code in nmdc_client/metadata.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
@requires_auth
def submit_json(self, json_records: list[dict] | str) -> int:
    """
    Submits a json file to the NMDC metadata database via the NMDC Runtime API's json_submit endpoint.

    Parameters
    ----------
    json_records
        The json records to be submitted. Can be passed in as a file path or list of dictionaries.

    Returns
    -------
    int
        The HTTP status code of the submission request.

    Raises
    ------
    Exception
        If the submission fails.

    """
    # if a file is passed in, load the json
    if isinstance(json_records, str):
        with open(json_records, "r") as f:
            json_records = json.load(f)

    token = self.auth.get_token()

    # api request
    url = f"{self.api_base_url}/metadata/json:submit"
    headers = self._build_http_request_headers(
        access_token=token,
        accept="application/json",
        content_type="application/json",
    )
    response = requests.post(url, headers=headers, json=json_records)

    # error handling
    if response.status_code != 200:
        logging.error(f"Request failed with response {response.text}")
        raise Exception(
            "Submission failed with the following information:\n"
            f"Status Code: {response.status_code}\n"
            f"Response: {response.text}"
        )
    else:
        logging.info("Submission passed!")

    return response.status_code

validate_json

validate_json(json_records: list[dict] | str) -> int

Validates a json file using the NMDC json validate endpoint.

If the validation passes, the method returns without any side effects.

Parameters:

Name Type Description Default
json_records list[dict] | str

The json records to be validated. Can be passed in as a file path or list of dictionaries.

required

Returns:

Type Description
int

The HTTP status code of the validation request.

Raises:

Type Description
Exception

If the validation fails.

Source code in nmdc_client/metadata.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def validate_json(self, json_records: list[dict] | str) -> int:
    """
    Validates a json file using the NMDC json validate endpoint.

    If the validation passes, the method returns without any side effects.

    Parameters
    ----------
    json_records
        The json records to be validated. Can be passed in as a file path or list of dictionaries.

    Returns
    -------
    int
        The HTTP status code of the validation request.

    Raises
    ------
    Exception
        If the validation fails.
    """
    if isinstance(json_records, str):
        with open(json_records, "r") as f:
            data = json.load(f)
    else:
        data = json_records

    # Check that the term "placeholder" is not present anywhere in the json
    if "placeholder" in json.dumps(data):
        raise Exception("Placeholder values found in json!")

    url = f"{self.api_base_url}/metadata/json:validate"
    headers = self._build_http_request_headers(
        accept="application/json",
        content_type="application/json",
    )
    response = requests.post(url, headers=headers, json=data)
    if response.text != '{"result":"All Okay!"}' or response.status_code != 200:
        logging.error(f"Validation failed.")
        raise Exception(
            f"Validation failed with the following information:\n"
            f"Status Code: {response.status_code}\n"
            f"Response: {response.text}"
        )
    else:
        logging.info("Validation passed!")

    return response.status_code

Identifier Minting

Minter

Minter(api_base_url: str = 'https://api.microbiomedata.org', auth: NMDCAuth | None = None, env: str = '')

Bases: nmdc_client.api_client.NMDCAPIClient

Class to interact with the NMDC API to mint new identifiers.

Parameters:

Name Type Description Default
api_base_url str

The base URL of the NMDC API.

'https://api.microbiomedata.org'
auth NMDCAuth | None

An instance of the NMDCAuth class for authentication.

None
Warnings

The env parameter is deprecated. Use api_base_url instead.

Source code in nmdc_client/minter.py
28
29
30
31
32
33
34
35
36
37
38
def __init__(
    self,
    api_base_url: str = API_BASE_URL,
    auth: NMDCAuth | None = None,
    env: str = "",
):
    super().__init__(
        api_base_url=api_base_url,
        env=env,
    )
    self.auth = auth or NMDCAuth(api_base_url=self.api_base_url)

mint

mint(nmdc_type: str, count: int = 1, client_id: str | None = None, client_secret: str | None = None) -> str | list[str]

Mint new identifier(s) for a specified type of record.

Parameters:

Name Type Description Default
nmdc_type str

The type of NMDC ID to mint (e.g., 'nmdc:MassSpectrometry', 'nmdc:DataObject').

required
count int

The number of identifiers to mint.

1
client_id str | None

The client ID for authentication. Kept for backwards compatibility.

None
client_secret str | None

The client secret for authentication. Kept for backwards compatibility.

None

Returns:

Type Description
str or list[str]

If count is 1, returns a single minted identifier as a string. If count is greater than 1, returns a list of minted identifiers.

Raises:

Type Description
RuntimeError

If the API request fails.

ValueError

If count is less than 1.

Notes

If client_id and client_secret are provided, a new instance of the NMDCAuth class will be created. The newest and preferred method for authentication is to use the NMDCAuth class directly.

Source code in nmdc_client/minter.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@requires_auth
def mint(
    self,
    nmdc_type: str,
    count: int = 1,
    client_id: str | None = None,
    client_secret: str | None = None,
) -> str | list[str]:
    """
    Mint new identifier(s) for a specified type of record.

    Parameters
    ----------
    nmdc_type
        The type of NMDC ID to mint (e.g., 'nmdc:MassSpectrometry',
        'nmdc:DataObject').
    count
        The number of identifiers to mint.
    client_id
        The client ID for authentication. Kept for backwards compatibility.
    client_secret
        The client secret for authentication. Kept for backwards compatibility.

    Returns
    -------
    str or list[str]
        If count is 1, returns a single minted identifier as a string.
        If count is greater than 1, returns a list of minted identifiers.

    Raises
    ------
    RuntimeError
        If the API request fails.
    ValueError
        If count is less than 1.

    Notes
    -----
    If ``client_id`` and ``client_secret`` are provided, a new instance of the ``NMDCAuth`` class will be created. The newest and preferred method for authentication is to use the ``NMDCAuth`` class directly.

    """
    # if they are passed into the function, create the auth object
    if client_id and client_secret:
        self.auth = NMDCAuth(
            client_id=client_id,
            client_secret=client_secret,
            api_base_url=self.api_base_url,
        )
    # Validate count parameter
    if count < 1:
        raise ValueError("count must be at least 1")

    # get the token
    token = self.auth.get_token()

    url = f"{self.api_base_url}/pids/mint"
    payload = {"schema_class": {"id": nmdc_type}, "how_many": count}
    try:
        response = requests.post(
            url,
            headers=self._build_http_request_headers(
                access_token=token,
                content_type="application/json",
            ),
            data=json.dumps(payload),
        )
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        logger.error("API request failed", exc_info=True)
        raise RuntimeError("Failed to mint new identifier from NMDC API") from e
    else:
        logging.debug(
            f"API request response: {response.json()}\n API Status Code: {response.status_code}"
        )
    # return the response
    response_data = response.json()
    if count == 1:
        return response_data[0]
    else:
        return response_data

Data Staging and Workflow Management

JGISequencingProjectAPI

JGISequencingProjectAPI(auth: NMDCAuth, api_base_url: str = 'https://api.microbiomedata.org', env: str = '')

Bases: nmdc_client.api_client.NMDCAPIClient

Class to interact with the NMDC API to get JGI samples.

Parameters:

Name Type Description Default
auth NMDCAuth

The NMDCAuth instance containing the credentials and API base URL for authentication.

required
api_base_url str

The base URL of an instance of the NMDC Runtime API. By default, this is the base URL of the production instance.

'https://api.microbiomedata.org'
env str

Deprecated. Use api_base_url instead. Previously used to specify the API environment (e.g., "prod", "dev").

''
Warnings

The env parameter is deprecated. Use api_base_url instead.

Source code in nmdc_client/data_staging.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def __init__(
    self,
    auth: NMDCAuth,
    api_base_url: str = API_BASE_URL,
    env: str = "",
):
    self.auth = auth
    if not self.auth.has_credentials():
        raise ValueError("credentials must be provided")
    super().__init__(
        api_base_url=api_base_url,
        env=env,
    )
    # make sure the `api_base_url` is the same
    # TODO: Use a global "settings" object to store the `api_base_url` in a single place.
    #       Example: https://github.com/pydantic/pydantic-settings
    if self.auth.api_base_url != self.api_base_url:
        raise ValueError(
            "`api_base_url` must be the same for NMDCAuth and JGISequencingProjectAPI"
        )

create_jgi_sequencing_project

create_jgi_sequencing_project(jgi_sequencing_project: dict) -> dict

Create a new JGI sequencing project in the NMDC database. For more information on available keys, visit the NMDC API Docs https://api.microbiomedata.org/docs#/Workflow%20management/create_sequencing_record_wf_file_staging_jgi_sequencing_projects_post

Parameters:

Name Type Description Default
jgi_sequencing_project dict

The JGI sequencing project data to be created.

required

Returns:

Type Description
dict

The created JGI sequencing project record.

Raises:

Type Description
Exception

If the creation fails.

Source code in nmdc_client/data_staging.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
@requires_auth
def create_jgi_sequencing_project(
    self,
    jgi_sequencing_project: dict,
) -> dict:
    """
    Create a new JGI sequencing project in the NMDC database.
    For more information on available keys, visit the NMDC API Docs
    https://api.microbiomedata.org/docs#/Workflow%20management/create_sequencing_record_wf_file_staging_jgi_sequencing_projects_post

    Parameters
    ----------
    jgi_sequencing_project
        The JGI sequencing project data to be created.

    Returns
    -------
    dict
        The created JGI sequencing project record.

    Raises
    ------
    Exception
        If the creation fails.
    """

    url = f"{self.api_base_url}/wf_file_staging/jgi_sequencing_projects"
    headers = self._build_http_request_headers(
        access_token=self.auth.get_token(),
        accept="application/json",
        content_type="application/json",
    )
    try:
        response = requests.post(url, headers=headers, json=jgi_sequencing_project)
        response.raise_for_status()
    except requests.RequestException as e:
        logger.error(f"Request failed: {e}")
        raise RuntimeError("Failed to add new JGI sequencing project") from e
    else:
        logging.debug(
            f"API request response: {response.json()}\n API Status Code: {response.status_code}"
        )

    return response.json()

get_jgi_sequencing_project_by_name

get_jgi_sequencing_project_by_name(project_name: str) -> dict

Get a specific JGI sequencing project by name.

Parameters:

Name Type Description Default
project_name str

The name of the JGI sequencing project to retrieve.

required

Returns:

Type Description
dict

The JGI sequencing project record.

Source code in nmdc_client/data_staging.py
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
@requires_auth
def get_jgi_sequencing_project_by_name(self, project_name: str) -> dict:
    """
    Get a specific JGI sequencing project by name.

    Parameters
    ----------
    project_name
        The name of the JGI sequencing project to retrieve.

    Returns
    -------
    dict
        The JGI sequencing project record.
    """
    url = f"{self.api_base_url}/wf_file_staging/jgi_sequencing_projects/{project_name}"
    headers = self._build_http_request_headers(
        access_token=self.auth.get_token(),
        accept="application/json",
        content_type="application/json",
    )
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
    except requests.RequestException as e:
        logger.error(f"Request failed: {e}")
        raise RuntimeError("Failed to retrieve JGI sequencing project") from e
    else:
        logging.debug(
            f"API request response: {response.json()}\n API Status Code: {response.status_code}"
        )

    return response.json()

list_jgi_sequencing_projects

list_jgi_sequencing_projects(filter: str | None = None, max_page_size: int = 20, fields: str = '', all_pages: bool = False) -> list[dict[str, Any]]

List JGI sequencing projects from the NMDC database.

Parameters:

Name Type Description Default
filter str | None

Filter to apply to the API call.

None
max_page_size int

The maximum number of items to return per page.

20
fields str

The fields to return.

''
all_pages bool

True to return all pages. False to return the first page.

False

Returns:

Type Description
list

The list of JGI sequencing projects.

Source code in nmdc_client/data_staging.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
@requires_auth
def list_jgi_sequencing_projects(
    self,
    filter: str | None = None,
    max_page_size: int = 20,
    fields: str = "",
    all_pages: bool = False,
) -> list[dict[str, Any]]:
    """
    List JGI sequencing projects from the NMDC database.

    Parameters
    ----------
    filter
        Filter to apply to the API call.
    max_page_size
        The maximum number of items to return per page.
    fields
        The fields to return.
    all_pages
        True to return all pages. False to return the first page.

    Returns
    -------
    list
        The list of JGI sequencing projects.
    """
    url = f"{self.api_base_url}/wf_file_staging/jgi_sequencing_projects"
    headers = self._build_http_request_headers(
        access_token=self.auth.get_token(),
        accept="application/json",
        content_type="application/json",
    )
    try:
        # Note: The `dict` is here to appease mypy, which, for some reason, doesn't infer that
        #       the dictionary being assigned here is sufficient to pass to `requests.get`.
        query_params: dict = {
            "filter": f"{json.dumps(filter)}",
            "max_page_size": max_page_size,
            "projection": fields,
        }
        response = requests.get(url, headers=headers, params=query_params)
        response.raise_for_status()
    except requests.RequestException as e:
        logger.error(f"Request failed: {e}")
        raise RuntimeError("Failed to retrieve JGI sequencing projects") from e
    else:
        logging.debug(
            f"API request response: {response.json()}\n API Status Code: {response.status_code}"
        )
    if all_pages:
        return self._get_all_pages(
            response,
            url,
            filter or "",
            max_page_size,
            fields,
            access_token=self.auth.get_token(),
        )["resources"]

    return response.json()["resources"]

JGISampleSearchAPI

JGISampleSearchAPI(auth: NMDCAuth, api_base_url: str = 'https://api.microbiomedata.org', env: str = '')

Bases: nmdc_client.api_client.NMDCAPIClient

Class to interact with the NMDC API to get JGI samples.

Parameters:

Name Type Description Default
auth NMDCAuth

The NMDCAuth instance containing the credentials and API base URL for authentication.

required
api_base_url str

The base URL of an instance of the NMDC Runtime API. By default, this is the base URL of the production instance.

'https://api.microbiomedata.org'
env str

Deprecated. Use api_base_url instead. Previously used to specify the API environment (e.g., "prod", "dev").

''
Warnings

The env parameter is deprecated. Use api_base_url instead.

Source code in nmdc_client/data_staging.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def __init__(
    self,
    auth: NMDCAuth,
    api_base_url: str = API_BASE_URL,
    env: str = "",
):
    self.auth = auth
    if not self.auth.has_credentials():
        raise ValueError("credentials must be provided")
    super().__init__(
        api_base_url=api_base_url,
        env=env,
    )
    # make sure the `api_base_url` is the same
    # TODO: Use a global "settings" object to store the `api_base_url` in a single place.
    #       Example: https://github.com/pydantic/pydantic-settings
    if self.auth.api_base_url != self.api_base_url:
        raise ValueError(
            "`api_base_url` must be the same for NMDCAuth and JGISampleSearchAPI"
        )

insert_jgi_sample

insert_jgi_sample(jgi_sample: dict) -> dict

Insert JGI samples into the NMDC database. For more information on keys, visit the NMDC API Docs https://api.microbiomedata.org/docs#/Workflow%20management/create_jgi_sample_wf_file_staging_jgi_samples_post

Parameters:

Name Type Description Default
jgi_sample dict

The JGI sample data to be inserted.

required

Returns:

Type Description
dict

The response from the insertion operation.

Raises:

Type Description
Exception

If the insertion fails.

Source code in nmdc_client/data_staging.py
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
@requires_auth
def insert_jgi_sample(
    self,
    jgi_sample: dict,
) -> dict:
    """
    Insert JGI samples into the NMDC database.
    For more information on keys, visit the NMDC API Docs
    https://api.microbiomedata.org/docs#/Workflow%20management/create_jgi_sample_wf_file_staging_jgi_samples_post

    Parameters
    ----------
    jgi_sample
        The JGI sample data to be inserted.

    Returns
    -------
    dict
        The response from the insertion operation.

    Raises
    ------
    Exception
        If the insertion fails.
    """
    url = f"{self.api_base_url}/wf_file_staging/jgi_samples"
    headers = self._build_http_request_headers(
        access_token=self.auth.get_token(),
        accept="application/json",
        content_type="application/json",
    )
    try:
        response = requests.post(url, headers=headers, json=jgi_sample)
        response.raise_for_status()
    except requests.RequestException as e:
        logger.error(f"Request failed: {e}")
        raise RuntimeError("Failed to insert JGI samples") from e
    else:
        logging.debug(
            f"API request response: {response.json()}\n API Status Code: {response.status_code}"
        )

    return response.json()

list_jgi_samples

list_jgi_samples(filter: str | None = None, max_page_size: int = 20, fields: str = '', all_pages: bool = False) -> list[dict]

Get a specific JGI sample by name.

Parameters:

Name Type Description Default
filter str | None

Filter to apply to the API call.

None
max_page_size int

The maximum number of items to return per page.

20
fields str

The fields to return.

''
all_pages bool

True to return all pages. False to return the first page.

False

Returns:

Type Description
list[dict]

The list of JGI sample records.

Source code in nmdc_client/data_staging.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
@requires_auth
def list_jgi_samples(
    self,
    filter: str | None = None,
    max_page_size: int = 20,
    fields: str = "",
    all_pages: bool = False,
) -> list[dict]:
    """
    Get a specific JGI sample by name.

    Parameters
    ----------
    filter
        Filter to apply to the API call.
    max_page_size
        The maximum number of items to return per page.
    fields
        The fields to return.
    all_pages
        True to return all pages. False to return the first page.

    Returns
    -------
    list[dict]
        The list of JGI sample records.
    """
    url = f"{self.api_base_url}/wf_file_staging/jgi_samples"
    try:
        query = filter if filter else {}
        query_params: dict[str, str | int] = {
            "filter": f"{json.dumps(query)}",
            "max_page_size": max_page_size,
            "projection": fields,
        }
        response = requests.get(
            url,
            headers=self._build_http_request_headers(
                access_token=self.auth.get_token(),
                accept="application/json",
                content_type="application/json",
            ),
            params=query_params,
        )
        response.raise_for_status()
    except requests.RequestException as e:
        logger.error(f"Request failed: {e}")
        raise RuntimeError("Failed to retrieve JGI samples") from e
    else:
        logging.debug(
            f"API request response: {response.json()}\n API Status Code: {response.status_code}"
        )
    if all_pages:
        return self._get_all_pages(
            response,
            url,
            filter or "",
            max_page_size,
            fields,
            self.auth.get_token(),
        )["resources"]

    return response.json()["resources"]

update_jgi_sample

update_jgi_sample(jgi_file_id: str, jgi_sample: dict) -> dict

Update JGI samples in the NMDC database. For more information on available keys, visit the NMDC API Docs https://api.microbiomedata.org/docs#/Workflow%20management/update_jgi_samples_wf_file_staging_jgi_samples__jdp_file_id__patch

Parameters:

Name Type Description Default
jgi_file_id str

The JGI file ID of the sample to be updated.

required
jgi_sample dict

The updated JGI sample data.

required

Returns:

Type Description
dict

The response from the update operation.

Raises:

Type Description
Exception

If the update fails.

Source code in nmdc_client/data_staging.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
@requires_auth
def update_jgi_sample(
    self,
    jgi_file_id: str,
    jgi_sample: dict,
) -> dict:
    """
    Update JGI samples in the NMDC database.
    For more information on available keys, visit the NMDC API Docs
    https://api.microbiomedata.org/docs#/Workflow%20management/update_jgi_samples_wf_file_staging_jgi_samples__jdp_file_id__patch

    Parameters
    ----------
    jgi_file_id
        The JGI file ID of the sample to be updated.
    jgi_sample
        The updated JGI sample data.

    Returns
    -------
    dict
        The response from the update operation.

    Raises
    ------
    Exception
        If the update fails.
    """
    url = f"{self.api_base_url}/wf_file_staging/jgi_samples/{jgi_file_id}"
    headers = self._build_http_request_headers(
        access_token=self.auth.get_token(),
        accept="application/json",
        content_type="application/json",
    )
    try:
        response = requests.patch(url, headers=headers, json=jgi_sample)
        response.raise_for_status()
    except requests.RequestException as e:
        logger.error(f"Request failed: {e}")
        raise RuntimeError("Failed to update JGI samples") from e
    else:
        logging.debug(
            f"API request response: {response.json()}\n API Status Code: {response.status_code}"
        )

    return response.json()

GlobusTaskAPI

GlobusTaskAPI(auth: NMDCAuth, api_base_url: str = 'https://api.microbiomedata.org', env: str = '')

Bases: nmdc_client.api_client.NMDCAPIClient

Class to interact with the NMDC API for Globus tasks.

Parameters:

Name Type Description Default
auth NMDCAuth

The NMDCAuth instance containing the credentials and API base URL for authentication.

required
api_base_url str

The base URL of an instance of the NMDC Runtime API. By default, this is the base URL of the production instance.

'https://api.microbiomedata.org'
env str

Deprecated. Use api_base_url instead. Previously used to specify the API environment (e.g., "prod", "dev").

''
Warnings

The env parameter is deprecated. Use api_base_url instead.

Source code in nmdc_client/data_staging.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
def __init__(
    self,
    auth: NMDCAuth,
    api_base_url: str = API_BASE_URL,
    env: str = "",
):
    self.auth = auth
    if not self.auth.has_credentials():
        raise ValueError("credentials must be provided")
    super().__init__(
        api_base_url=api_base_url,
        env=env,
    )
    # make sure the `api_base_url` is the same
    # TODO: Use a global "settings" object to store the `api_base_url` in a single place.
    #       Example: https://github.com/pydantic/pydantic-settings
    if self.auth.api_base_url != self.api_base_url:
        raise ValueError(
            "`api_base_url` must be the same for NMDCAuth and GlobusTaskAPI"
        )

create_globus_task

create_globus_task(globus_task: dict) -> dict

Create a new Globus task in the NMDC database. For more information on available keys, visit the NMDC API Docs https://api.microbiomedata.org/docs#/Workflow%20management/create_globus_tasks_wf_file_staging_globus_tasks_post

Parameters:

Name Type Description Default
globus_task dict

The Globus task data to be created.

required

Returns:

Type Description
dict

The created Globus task record.

Raises:

Type Description
Exception

If the creation fails.

Source code in nmdc_client/data_staging.py
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
@requires_auth
def create_globus_task(
    self,
    globus_task: dict,
) -> dict:
    """
    Create a new Globus task in the NMDC database.
    For more information on available keys, visit the NMDC API Docs
    https://api.microbiomedata.org/docs#/Workflow%20management/create_globus_tasks_wf_file_staging_globus_tasks_post

    Parameters
    ----------
    globus_task
        The Globus task data to be created.

    Returns
    -------
    dict
        The created Globus task record.

    Raises
    ------
    Exception
        If the creation fails.
    """

    url = f"{self.api_base_url}/wf_file_staging/globus_tasks"
    headers = self._build_http_request_headers(
        access_token=self.auth.get_token(),
        accept="application/json",
        content_type="application/json",
    )
    try:
        response = requests.post(url, headers=headers, json=globus_task)
        response.raise_for_status()
    except requests.RequestException as e:
        logger.error(f"Request failed: {e}")
        raise RuntimeError("Failed to add new Globus task") from e
    else:
        logging.debug(
            f"API request response: {response.json()}\n API Status Code: {response.status_code}"
        )

    return response.json()

list_globus_tasks

list_globus_tasks(filter: str | None = None, max_page_size: int = 20, fields: str = '', all_pages: bool = False) -> list[dict]

Get Globus tasks from the NMDC database.

Parameters:

Name Type Description Default
filter str | None

Filter to apply to the API call.

None
max_page_size int

The maximum number of items to return per page.

20
fields str

The fields to return.

''
all_pages bool

True to return all pages. False to return the first page.

False

Returns:

Type Description
list[dict]

The list of Globus task records.

Source code in nmdc_client/data_staging.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
@requires_auth
def list_globus_tasks(
    self,
    filter: str | None = None,
    max_page_size: int = 20,
    fields: str = "",
    all_pages: bool = False,
) -> list[dict]:
    """
    Get Globus tasks from the NMDC database.

    Parameters
    ----------
    filter
        Filter to apply to the API call.
    max_page_size
        The maximum number of items to return per page.
    fields
        The fields to return.
    all_pages
        True to return all pages. False to return the first page.

    Returns
    -------
    list[dict]
        The list of Globus task records.
    """
    url = f"{self.api_base_url}/wf_file_staging/globus_tasks"
    headers = self._build_http_request_headers(
        access_token=self.auth.get_token(),
        accept="application/json",
        content_type="application/json",
    )
    query_params: dict[str, str | int] = {
        "filter": f"{json.dumps(filter)}",
        "max_page_size": max_page_size,
        "projection": fields,
    }
    try:
        response = requests.get(url, headers=headers, params=query_params)
        response.raise_for_status()
    except requests.RequestException as e:
        logger.error(f"Request failed: {e}")
        raise RuntimeError("Failed to retrieve Globus tasks") from e
    else:
        logging.debug(
            f"API request response: {response.json()}\n API Status Code: {response.status_code}"
        )
    if all_pages:
        return self._get_all_pages(
            response,
            url,
            filter or "",
            max_page_size,
            fields,
            self.auth.get_token(),
        )["resources"]
    return response.json()["resources"]

update_globus_task

update_globus_task(globus_task_id: str, globus_task: dict) -> dict

Update a Globus task in the NMDC database. For more information on available keys, visit the NMDC API Docs https://api.microbiomedata.org/docs#/Workflow%20management/update_globus_tasks_wf_file_staging_globus_tasks__task_id__patch

Parameters:

Name Type Description Default
globus_task_id str

The ID of the Globus task to be updated.

required
globus_task dict

The Globus task data to be updated.

required

Returns:

Type Description
dict

The updated Globus task record.

Raises:

Type Description
Exception

If the update fails.

Source code in nmdc_client/data_staging.py
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
@requires_auth
def update_globus_task(
    self,
    globus_task_id: str,
    globus_task: dict,
) -> dict:
    """
    Update a Globus task in the NMDC database.
    For more information on available keys, visit the NMDC API Docs
    https://api.microbiomedata.org/docs#/Workflow%20management/update_globus_tasks_wf_file_staging_globus_tasks__task_id__patch

    Parameters
    ----------
    globus_task_id
        The ID of the Globus task to be updated.
    globus_task
        The Globus task data to be updated.

    Returns
    -------
    dict
        The updated Globus task record.

    Raises
    ------
    Exception
        If the update fails.
    """
    url = f"{self.api_base_url}/wf_file_staging/globus_tasks/{globus_task_id}"
    headers = self._build_http_request_headers(
        access_token=self.auth.get_token(),
        accept="application/json",
        content_type="application/json",
    )
    try:
        response = requests.patch(url, headers=headers, json=globus_task)
        response.raise_for_status()
    except requests.RequestException as e:
        logger.error(f"Request failed: {e}")
        raise RuntimeError("Failed to update Globus task") from e
    else:
        logging.debug(
            f"API request response: {response.json()}\n API Status Code: {response.status_code}"
        )

    return response.json()