Integrate madbot in your Python code
Ce contenu n’est pas encore disponible dans votre langue.
A platform whose own tool already knows what it produced (a LIMS, a pipeline runner, an acquisition software) may rather call madbot from its code than write a deposit file. The madbot_cli library gives each step of a deposit as a Python function: this page chains them in a script, from the node to the identifiers the repository returns.
The script is the example cli/examples/integration/integrate.py. The madbot CI runs it twice at each merge request that touches the library, against test plugins that stand for the source and the repository, and checks that the second run creates nothing. The excerpts below are read from it when this site is built.
Before you start
Section titled “Before you start”- The address of the API of your instance and a personal access token with the
readandwritescopes: see Get started with the REST API. - madbot 2.2.0 or later, with a plugin for your source and one for your repository.
- uv, or Python 3.10 or later with
madbot-cliinstalled as the tutorial shows. The library needs nothing else.
The example
Section titled “The example”As it is, the script reads a public record of Zenodo (a year of water quality measurements of a stream, in three files), makes one sample per station from a table, and deposits the files on a demonstration server, where nothing is published. Its PARAMS, at the top, say all of it: the workspace and the node, the source and the files, the table of the samples, the repository, its settings and the metadata values. Change them for your own source and repository.
The table stands for an export of your tool: one row per sample, with its name, its title, the files it is bound to, and any value its metadata needs.
sample,title,files,latitude,longitudeST1,Amont du moulin,mesures.csv,45.1612,1.5274ST2,Pont de la départementale,mesures.csv,45.1489,1.5531ST3,Confluence,mesures.csv,45.1301,1.5896Run the script with the address and the token of madbot, and the credentials of the repository, in the environment:
export MADBOT_API=https://api.madbot.example.orgexport MADBOT_TOKEN=pat_…export RECHERCHE_DATA_GOUV_CREDENTIALS='{"token": "…"}'uv run integrate.py # prepares the submission, sends nothinguv run integrate.py --submit # also sends it to the repositoryThe script declares what it needs in a header of comments, in the standard format of Python scripts: Python 3.10 or later, and madbot-cli from the package registry of madbot. uv run reads it, takes a suitable Python, fetching one when needed, and installs madbot-cli in an environment of its own: the Python of your system, however old, is left alone. Keep this header when you copy the script into your tool. Without uv, run python integrate.py in an environment where madbot-cli is installed.
Or import it in a Python console and call the steps one by one, to see what each returns.
Find before you create
Section titled “Find before you create”madbot recognises a node and a submission by their title, and a sample by its alias. Without a deposit file, nothing compares your code with what madbot holds: each step looks for what it needs before creating it, so that the script can run after every new series of data. link_data leaves alone the data a node already holds, and a connection is given back when the workspace already has one with the same plugin and shared parameters.
1. Connect to madbot
Section titled “1. Connect to madbot”def connect_to_madbot(**options: Any) -> Client: client = Client.from_env(**options) version = client.check_version() if version["compatible"] is False: msg = f"madbot {version['version']} is too old for this madbot-cli." raise MadbotError(msg) return clientClient.from_env reads MADBOT_API and MADBOT_TOKEN. There is no default address, so that nothing is written to an instance you did not name.
2. The workspace and the node
Section titled “2. The workspace and the node”def ensure_node( client: Client, workspace: str, title: str, description: str | None = None) -> dict: found = op.find_workspace(client, workspace) or op.create_workspace( client, workspace ) client.use_workspace(found["id"]) return op.find_node(client, title) or op.create_node(client, title, description)The client acts in the workspace from then on: every request carries it in the X-Workspace header.
3. Link the data
Section titled “3. Link the data”def link_files( client: Client, node: Mapping, spec: Mapping[str, Any], log: Log = print) -> dict[str, dict]: connection = connect_plugin(client, spec) parent = op.browse_path(client, connection["id"], spec["path"]) children = {c["name"]: c for c in op.browse(client, connection["id"], parent)} for name in spec["names"]: if name not in children: msg = ( f"No {name!r} there. {op.found_instead(name, list(children.values()))}" ) raise MadbotError(msg) wanted = {children[name]["id"]: name for name in spec["names"]} answers = op.link_data( client, node["id"], connection["id"], [{"external_id": i, "name": n} for i, n in wanted.items()], ) log(f"linked {sum(a.get('created', 0) for a in answers)} new files") op.wait_for_data(client, [a.get("task_id") for a in answers]) linked = {} for datalink in op.list_datalinks(client, node["id"]): data = datalink["data"] if data.get("external_id") not in wanted: continue if data.get("status") == op.DATA_FAILED: msg = f"madbot could not read {data.get('name')}: {data.get('enrichment_error')}" raise MadbotError(msg) linked[wanted[data["external_id"]]] = datalink return linkedbrowse_path opens the containers of path from the root of the source; a public record that the root does not list is found by searching. The files are linked in one request per thousand, then madbot reads them from the source in the background: wait_for_data waits for it. A file madbot could not read stops the script with its reason.
The credentials of a source or a repository come from an environment variable, as a JSON object, never from the code:
def credentials_from(env: str | None) -> dict | None: if env is None: return None if not os.environ.get(env): msg = ( f"Give the credentials in the {env} environment variable, as a JSON object." ) raise MadbotError(msg) try: credentials = json.loads(os.environ[env]) except json.JSONDecodeError as error: msg = f"The {env} environment variable is not valid JSON: {error}." raise MadbotError(msg) from error if not isinstance(credentials, dict): msg = f"The {env} environment variable must hold a JSON object." raise MadbotError(msg) return credentials4. Samples from a table
Section titled “4. Samples from a table”def ensure_samples( client: Client, node: Mapping, rows: list[Mapping[str, str]], linked: Mapping[str, Mapping], log: Log = print,) -> dict[str, dict]: samples = {s["alias"]: s for s in op.list_samples(client, node["id"])} for row in rows: alias = op.alias_of(row["sample"]) if alias not in samples: samples[alias] = op.create_sample(client, node["id"], row["title"], alias) log(f"created sample {alias}") for name in filter(None, (n.strip() for n in row["files"].split(";"))): if name not in linked: msg = f"Sample {row['sample']}: {name!r} is not linked to the node." raise MadbotError(msg) datalink = linked[name] if op.bind_sample( client, datalink["data"]["id"], datalink["id"], samples[alias]["id"] ): log(f"bound sample {alias} to {name}") return samplesalias_of makes the alias of a sample from its name, as the web application does, so that a sample created by hand is found too. There is no batch request for samples yet: the script sends one request per sample and per file it is bound to.
5. The submission and its metadata
Section titled “5. The submission and its metadata”def ensure_submission( client: Client, spec: Mapping[str, Any], linked: Mapping[str, Mapping]) -> dict: repository = connect_plugin(client, spec["repository"]) submission = op.find_submission( client, spec["title"], repository["id"] ) or op.create_submission( client, spec["title"], repository["id"], spec["repository"].get("settings") ) submission = op.wait_submission(client, submission["id"]) if submission.get("status") in DEPOSITED: return submission # A deposit does not change any more. held = { op.object_id(d.get("datalink")) for d in op.list_submission_data(client, submission["id"]) } new = [d for d in linked.values() if d["id"] not in held] if new: op.add_submission_data(client, submission["id"], new) return op.wait_submission(client, submission["id"])Once its data are in it, madbot makes the metadata objects the repository asks for, and fills what it already knows. The script gives the rest: the values of each type from PARAMS, and for each sample object the values of its row in the table, through sample_columns. Recherche Data Gouv asks for no values per sample, so the example leaves sample_columns empty; for a repository that does, map each column of the table to the slug of a field.
def values_of( metadata_object: Mapping, spec: Mapping[str, Any], rows: list[Mapping[str, str]],) -> dict[str, Any]: values = dict(spec.get("metadata", {}).get(metadata_object.get("type")) or {}) if metadata_object.get("type") == spec.get("sample_type"): names = {str(v) for v in (metadata_object.get("summary_fields") or {}).values()} for row in rows: if op.alias_of(row["sample"]) in names or row["sample"] in names: values.update( { slug: row[column] for column, slug in spec.get("sample_columns", {}).items() if row.get(column) } ) return valuesdef fill_metadata( client: Client, submission: Mapping, spec: Mapping[str, Any], rows: list[Mapping[str, str]],) -> dict: if submission.get("status") in DEPOSITED: return dict(submission) for metadata_object in op.list_metadata_objects(client, submission["id"]): values = values_of(metadata_object, spec, rows) if values: op.set_metadata(client, submission["id"], metadata_object["id"], values) op.generate_metadata(client, submission["id"]) return op.wait_submission(client, submission["id"])To know which fields a repository asks for, run the script without --submit, then list what is still missing:
from madbot_cli import operations as op
for metadata_object in op.missing_metadata(client, submission["id"]): print(metadata_object["type"], [f["slug"] for f in metadata_object["missing"]])madbot-cli field <slug> tells what a field accepts, with an example value.
6. Submit
Section titled “6. Submit”def submit(client: Client, submission: Mapping) -> dict: if submission.get("status") not in DEPOSITED: missing = op.missing_metadata(client, submission["id"]) if submission.get("status") != "ready" or missing: fields = sorted({f["slug"] for o in missing for f in o["missing"]}) msg = ( f"The submission is {submission.get('status')}, not ready. " f"Mandatory values missing: {', '.join(fields) or 'none'}." ) raise MadbotError(msg) op.submit(client, submission["id"]) submission = op.wait_submission(client, submission["id"]) if submission.get("status") not in DEPOSITED: msg = ( "The repository refused the submission: " f"{submission.get('error_reason') or submission.get('status')}" ) raise MadbotError(msg) return dict(submission)Sending cannot be undone. The script sends only with --submit, and only a submission madbot found ready; a submission already sent is not sent again. The identifiers the repository returns, such as a DOI, are in its external_identifiers.
Run it again
Section titled “Run it again”Run the script a second time: it finds the node, the data, the samples and the submission, writes the same values again, and creates nothing. Add a file to names or a row to the table, and only that is linked or created. A submission already sent does not change: madbot cannot update a deposit yet, so new data go in a new submission, under another title.
In your own tool
Section titled “In your own tool”- Call
main, or each step, from a task of your tool, with the parameters it knows: the files of a run, the samples of a batch, the values of its records. - Keep the secrets out of the code: the madbot token and the credentials of each source and repository are secrets of your tool, given in the environment.
- Handle the errors: a step raises
MadbotErrorwith a message for a person;ApiError,TaskFailedandWaitTimeout, all inmadbot_cli.errors, tell a refused request, a failed background task and a wait too long apart. - Prefer the deposit file when your platform writes one file per series of data:
madbot-cli planthen shows what would change before anything is written, andapplydoes the comparisons of this script for you. See Submit data to a repository, end to end.
The library reference describes every function of madbot_cli.operations.

