Python API client
Install and configure the ionworks Python package: authentication, dataframe backend, retries, and sub-clients reference
The ionworks Python package
provides a programmatic interface for managing resources, running simulations,
submitting pipelines, and uploading data in Ionworks Studio.
Installation
pip install ionworksionworks requires Python 3.12 or later. It replaces the ionworks-api,
ionworks-schema, ionworksdata and iwutil packages, and cannot share an
environment with ionworks-api; if you have those installed, see the
migration guide.
Describing pipelines: ionworks.pipeline
ionworks.api submits work and collects results. To describe a fit or a
validation, use ionworks.pipeline, which
provides the typed building blocks — Pipeline, DataFit, objectives, costs,
and optimizers.
import ionworks as iw
pipeline = iw.pipeline.Pipeline(
elements={
"fit": iw.pipeline.DataFit(
objectives={"cycle": iw.pipeline.objectives.CurrentDriven(
data_input="file:path/to/discharge.csv",
options={"model": "SPM"},
)},
parameters={
"Negative particle diffusivity [m2.s-1]": iw.pipeline.Parameter(
"Negative particle diffusivity [m2.s-1]",
bounds=(1e-14, 1e-13),
initial_value=2e-14,
),
},
cost=iw.pipeline.costs.RMSE(),
),
},
name="Diffusivity fit",
)
client = iw.api.Client()
submission = client.pipeline.create(pipeline)
client.pipeline.wait_for_completion(submission.id)
fit = client.pipeline.result(submission.id).element("fit")
print(fit.parameter_values)See the Pipelines API how-to for submission options, polling, and plotting results, or Which package do I need? if you are not sure which of these you want.
Authentication
Get your API key from the Ionworks account settings and configure it:
import ionworks as iw
# Option 1: Environment variable (recommended)
# Set IONWORKS_API_KEY in your shell environment before constructing the client
client = iw.api.Client()
# Option 2: Direct configuration
client = iw.api.Client(api_key="your_key")
# Option 3: Custom timeout and retry settings
client = iw.api.Client(
timeout=30, # Request timeout in seconds (default: 10)
max_retries=3 # Max retries on failure (default: 5)
)Never commit API keys to version control. Use environment variables or a secrets manager for credential management.
API keys are valid for one year. The expiry date is shown next to your key
in account settings, and the page warns you when a key is within 30 days of
expiring. Regenerating a key resets its expiry and invalidates the
previous key, so update any integration that uses it. An expired key returns
401 with a message saying the key has expired.
Importing ionworks does not auto-load a .env file. Set IONWORKS_API_KEY in your shell
environment, load the .env file yourself (for example with
python-dotenv) before
constructing the client, or pass api_key= explicitly to iw.api.Client(...).
Verify your API key
Use client.whoami() to confirm which user and organization the configured
API key resolves to. This is the recommended way to debug 401/403 errors,
or to check why you're seeing data from the wrong organization.
me = client.whoami()
print(me["email"], me["authorized_organization"])
# alice@example.com {'id': 'org_abc123', 'name': 'Acme Battery'}The response has two organization fields and the distinction matters:
authorized_organization— the org this request is authorized as. For SDK calls, this is the org the configured API key was issued for, and is the source of truth for permission checks on every request the client makes. It'sNoneif no org context could be resolved.organizations— the user's full membership list (every org they belong to). This is a different question and is not what permission checks run against.
If the id or name in authorized_organization doesn't match what you
expect, the wrong key is in use — regenerate one for the correct org from
your account settings.
Default project
Most sub-clients (pipelines, studies, optimizations, cell specifications, ...)
operate within a project. Rather than
threading a project_id through every call, you can configure a default once
on the client. Sub-client methods that take a project_id argument fall back
to this default when one isn't passed explicitly.
The client resolves the default in this order:
- The
project_id=argument passed toiw.api.Client(...). - The
IONWORKS_PROJECT_IDenvironment variable. - Otherwise, no default is set — methods that need a project will raise
ValueErrorunlessproject_idis passed at the call site.
import ionworks as iw
# Option 1: Environment variable (recommended)
# Set IONWORKS_PROJECT_ID in your environment or .env file
client = iw.api.Client()
# Option 2: Pass to the client constructor
client = iw.api.Client(project_id="your-project-id")
# Override on a per-call basis when needed
client.study.list(project_id="other-project-id")You can find your project ID in the URL of the project settings page:
https://app.ionworks.com/projects/<project-id>/settings.
The PROJECT_ID environment variable is still accepted for backwards
compatibility but is deprecated. Set IONWORKS_PROJECT_ID instead — using
the old name emits a DeprecationWarning and will stop working in a future
release.
Environment variables
The client reads the following variables from your shell environment when
constructed. .env files are not loaded automatically — populate the
environment yourself (for example by sourcing the file, or by calling
python-dotenv) before
constructing the client.
| Variable | Required | Default | Description |
|---|---|---|---|
IONWORKS_API_KEY | Yes | — | API key from your account settings. |
IONWORKS_API_URL | No | https://api.ionworks.com | API base URL. |
IONWORKS_PROJECT_ID | For project-scoped calls | — | Default project ID for sub-client methods. |
IONWORKS_DATAFRAME_BACKEND | No | polars | DataFrame backend: polars or pandas. |
DataFrame backend
By default, the client returns data as polars DataFrames. You can switch to pandas if your workflow requires it.
import ionworks as iw
# Option 1: Set via constructor
client = iw.api.Client(dataframe_backend="pandas")
# Option 2: Set via environment variable
# IONWORKS_DATAFRAME_BACKEND=pandas
# Option 3: Set at runtime
iw.api.set_dataframe_backend("pandas")
print(iw.api.get_dataframe_backend()) # "pandas"All methods that return DataFrames (time series, steps, cycles) respect this setting.
Timeout and retry behavior
The client automatically retries failed requests on connection errors, timeouts, and server errors (5xx). By default:
- Requests time out after 10 seconds
- Failed requests retry up to 5 times with exponential backoff
- Dropped connections (the server closed the socket before the request reached the application — common on reused keep-alive connections) are retried for all methods, including POST and PATCH. The request never reached the server, so resending is safe.
- Read timeouts and 5xx responses are only retried for idempotent methods (GET and DELETE). The server may have already processed a POST or PATCH, so resubmitting could duplicate the operation.
You can customize these settings:
import ionworks as iw
# Longer timeout for large uploads
client = iw.api.Client(timeout=60)
# Disable retries
client = iw.api.Client(max_retries=0)Sub-clients
The client exposes domain-specific sub-clients:
| Sub-client | Access | Documentation |
|---|---|---|
| Projects | client.project | Projects API |
| Organization usage and members | client.organization | Organizations |
| Models | client.model | Build API |
| Parameterized models | client.parameterized_model | Build API |
| Studies | client.study | Simulate API |
| Protocols | client.protocol | Protocol API |
| Simulations | client.simulation | Simulate API |
| Pipelines | client.pipeline | Pipelines API |
| Optimizations | client.optimization | Optimize API |
| Cell specifications | client.cell_spec | Uploading data |
| Cell instances | client.cell_instance | Uploading data |
| Cell measurements | client.cell_measurement | Measurements |
| Sites | client.site | Lab view |
| Cyclers | client.cycler | Lab view |
| Channels | client.channel | Lab view |
| Lab occupancy | client.lab | Lab view |
| Planned measurements | client.planned_measurement | Planned measurements |
| Analyses | client.analysis | Analyses |
| Materials | client.material | Materials & property datasets |
| Material property datasets | client.material_property_dataset | Materials & property datasets |
| Jobs | client.job | Canceling jobs |
| Search | client.search | Searching across your organization |
| Web app links | .get() on any client, or client.urls | Linking to the web app |
Searching across your organization
client.search.query() finds entities by name or description across your whole
organization in one call, without knowing which sub-client to reach for:
response = client.search.query("LGM50")
for result in response.results:
print(result.entity_type, result.id, result.name)Name fields match on case-insensitive substring; descriptions and notes match on a prefix full-text search. Substring matches rank ahead of full-text matches within each entity type.
Searchable entity types are project, model, cell_specification,
cell_instance, cell_measurement, parameterized_model,
experiment_template, optimization_template, material, study,
optimization, and pipeline.
| Parameter | Default | Description |
|---|---|---|
q | — | Query string. Must be at least two characters. |
limit | 25 | Results per page (1–100). |
offset | 0 | Results to skip, for pagination. |
per_type | 5 | Maximum results per entity type (1–20), so one type cannot crowd out the rest. |
entity_types | all | Restrict to specific entity types. |
project_id | none | Restrict everything that belongs to a project (parameterized models, protocols, cell data, studies, optimizations, pipelines) to that one. Rows with no project, such as built-in templates, are kept. |
# Only measurements and instances, 10 of each
response = client.search.query(
"aging",
entity_types=["cell_measurement", "cell_instance"],
per_type=10,
)Unlike most sub-clients, search does not fall back to the client's
default project — it spans the whole organization unless you pass
project_id. Results are always limited to what your account can already
read.
Discovering the API
client.capabilities() and client.schema(name) describe the API from the
API itself. Use them from a notebook or script to introduce yourself — or a
coding agent you're scripting against — to the platform's data hierarchy and
to fetch the authoritative JSON Schemas for measurements and UCP protocols.
caps = client.capabilities()
print(caps["domain_context"]["hierarchy"])
# organization -> project -> cell_specification -> cell_instance
# -> cell_measurement -> [time_series, steps, cycles, analysis] ...
# Standard time-series column names, required fields, sign conventions
data_schema = client.schema("data")
# Full UCP JSON Schema plus runnable examples
protocol_schema = client.schema("protocol")capabilities() also returns pointers to the OpenAPI spec
(/openapi.json) and per-resource JSON Schema endpoints under
caps["schemas"], so agents can fetch the exact shape of any create/update
payload before calling it.
Coding agents driving Ionworks should call client.capabilities() and
client.schema(name) before generating request bodies — the responses
reflect the running server, so agents never guess at endpoint shapes or
column names that may have drifted.
Linking to the web app
Every resource you fetch with .get() carries two links: url, its page in
the Ionworks web app (Ionworks Studio), and api_url, the API endpoint that
returns it. Use url to surface clickable links from notebooks, scripts,
dashboards, or Slack/email reports so collaborators can jump straight to the
resource.
pm = client.parameterized_model.get("pm_123")
pm.url
# https://app.ionworks.com/projects/proj_abc/parameterized-models/pm_123
pm.api_url
# https://api.ionworks.com/parameterized_models/pm_123The server builds both links from the record itself, so you don't need to know how the web app lays out its pages, or — except for studies — which project a resource belongs to.
| Fetch | url links to |
|---|---|
client.project.get(project_id) | Project home page. |
client.study.get(study_id, project_id=None) | Study detail page. Studies are fetched within a project, so pass project_id unless the study is in the client's default project. |
client.model.get(model_id) | Model detail page. None for built-in models, which belong to no project. |
client.parameterized_model.get(parameterized_model_id) | Parameterized model detail page. |
client.simulation.get(simulation_id) | Simulation detail page, nested under its parameterized model. |
client.protocol.get(protocol_id) | Protocol detail page. |
client.pipeline.get(pipeline_id) | Pipeline detail page. |
client.optimization.get(optimization_id) | Optimization detail page. |
client.material.get(material_id) | Material detail page. |
client.cell_spec.get(spec_id) | Cell instances list for that specification. |
client.cell_instance.get(instance_id) | Measurements list for that instance. |
client.cell_measurement.get(measurement_id) | Measurement detail page. |
client.simulation.get() and client.optimization.get() return dictionaries,
so read ["url"] instead of .url.
Only .get() responses carry links. Items returned by .list() and the
responses from .create() do not — fetch the resource when you need its link.
Building links from IDs
When you hold only an ID and want a link without an API request, client.urls
builds the same URLs locally. It is a fallback: prefer the url from .get(),
which is correct even when you don't know the resource's project.
import ionworks as iw
client = iw.api.Client(project_id="proj_abc")
client.urls.study("study_xyz")
# https://app.ionworks.com/projects/proj_abc/studies/study_xyzEach helper takes the resource's own ID plus whatever parent IDs the route
requires. project_id is optional — it falls back to the
default project configured on the client. The web-app host
is derived from the client's API URL (api.ionworks.com → app.ionworks.com);
set IONWORKS_APP_URL to override it, for example in local development.
| Helper | Returns a link to |
|---|---|
client.urls.project(project_id=None) | Project studies list. |
client.urls.study(study_id, project_id=None) | Study detail page. |
client.urls.model(model_id, project_id=None) | Model detail page. |
client.urls.parameterized_model(parameterized_model_id, project_id=None) | Parameterized model detail page. |
client.urls.simulation(simulation_id, parameterized_model_id=None, project_id=None) | Simulation detail page (nested under its parameterized model). |
client.urls.protocol(protocol_id, project_id=None) | Protocol detail page. |
client.urls.pipeline(pipeline_id, project_id=None) | Pipeline detail page. |
client.urls.optimization(optimization_id, project_id=None) | Optimization detail page. |
client.urls.material(material_id, project_id=None) | Material detail page. |
client.urls.cell_specs(project_id=None) | Cell specifications list page. |
client.urls.cell_instances(spec_id, project_id=None) | Cell instances list page nested under a spec. |
client.urls.measurement(measurement_id, project_id=None) | Measurement detail page. |
A simulation's page is nested under its parameterized model. Pass
parameterized_model_id to build the link locally; without it,
client.urls.simulation() fetches the simulation and returns the url it
carries.
Canceling jobs
You can cancel running jobs (simulations, pipelines, and optimizations) using the Python API. Each job has a unique ID that you can use to cancel it.
# Cancel a job by ID
client.job.cancel(job_id="job_abc123")Cancelling a parent job automatically cancels all of its child jobs. For example, cancelling a pipeline cancels all of its running elements.
Resubmitting a failed pipeline
If a pipeline stops because its first failed element could not be submitted
(error_code = SUBMISSION_FAILED), you can resubmit it without rebuilding the
configuration. Completed elements are preserved; execution resumes from the
failed element.
The Python client does not yet expose a resubmit method, so call the REST
endpoint directly as a temporary workaround. Resubmission goes through the
generic jobs endpoint, and a pipeline is identified by its job ID — the same
ID you pass to client.pipeline.get(...):
curl -X POST \
-H "Authorization: Bearer $IONWORKS_API_KEY" \
https://api.ionworks.com/jobs/{pipeline_id}/resubmitResubmission only applies to SUBMISSION_FAILED errors. For execution
timeouts or configuration mistakes, create a new pipeline with the corrected
configuration. For internal errors, wait briefly and create a new pipeline if
the issue persists. See Handling pipeline
failures for details.
Retrieving job metadata
Standard job-detail responses strip fields that can grow large — submitted
configs, full result payloads, and serialized PyBaMM models — so listing
and polling stay fast even for pipelines or optimizations with heavy inline
data. When you actually need those fields, fetch them with
client.job.get_metadata:
# Fetch the full, untruncated metadata for a job
metadata = client.job.get_metadata(job_id="job_abc123")
# Validation payloads, when present
plot_config = metadata.get("validation_plot_config")
series_index = metadata.get("validation_series_index")Use this when you need to:
- Re-run a job from its original submitted config without keeping a local copy.
- Audit the exact inputs that produced a result.
- Read large result blobs — for example, optimization traces, or the
validation_plot_configproduced by pipeline validations — that aren't included in the default job response.
A validation element's time series are not on this blob. They are stored
per objective, and validation_series_index is the list of what exists. The
normal way to read them is off the typed result object —
client.pipeline.result(pipeline_id).element("validate").series returns
{objective: {source: {channel: [values]}}} at full resolution — source
being "optimal" or "baseline" — and .overlay returns the decimated data
behind the plots. Drop to
client.pipeline.get_element_series_channels and
client.pipeline.get_element_series when you want to fetch one named
objective instead of every sample of every objective.
The returned object is a plain dict parsed from the job's
metadata.json.gz blob. If a job has no metadata file (for example, it
failed before writing one) the call raises an error — wrap it in a
try/except if you're iterating over many jobs.
For pipelines, client.pipeline.result(pipeline_id) is still the easiest
way to get parsed, fitted parameter values. Use client.job.get_metadata
when you need the raw, unparsed payload backing a job.
Retrieving MCMC posterior samples
Data-fit jobs that use a sampler (for example, PintsSampler) evaluate
many parameter vectors rather than converging on a single point
estimate. The resulting chain is too large for the standard job result
column, so it is offloaded to the job's metadata blob.
For a fit you have the pipeline result for, the typed PosteriorResult
is the shorter path — result.element("<name>").chains gives the
(chain, draw, parameter) samples and .marginal("<parameter>") gives
one parameter's post-burn-in distribution, rebuilding both from the
offloaded payload when needed. Reach for the raw dict below when you
have only a job_id, or want the chain without the result object.
The raw chain is retrieved with client.job.get_posterior_samples:
import numpy as np
# Fetch the sample chain for a sampler-based datafit
samples = client.job.get_posterior_samples(job_id="job_abc123")
chain = samples["samples"] # dict[str, list] keyed by parameter name
costs = samples["sample_costs"] # cost per sample
param_names = samples["sample_param_names"] # parameter names in column order
burnin = samples["sample_burnin"] or 0 # burn-in length (may be None)
# The chain is 2-D (start, iteration) for a multistart fit and 1-D
# (iteration,) for a single start, so drop burn-in off the last axis.
post_burnin = {k: np.asarray(v)[..., burnin:] for k, v in chain.items()}The returned dict has four keys:
samples— the chain as adict[str, list], keyed by parameter name. Each value is a nested list of shape(starts, iterations)for a multistart fit, and a flat list of lengthiterationswhen the fit ran a single start. Index the iteration axis last ([..., burnin:]) so both shapes work.sample_costs— the objective value at each sample, in the same shape as one parameter's chain.sample_param_names— the parameter names in column order.sample_burnin— the number of initial iterations the sampler treats as burn-in. The chain includes them; discard them before downstream analysis. This isNonefor samplers that have no burn-in concept (GridSearch,PointEstimateSampler), so guard against it (e.g.burnin = samples["sample_burnin"] or 0) before using it as a slice boundary.
Every sampler-based fit populates these fields — not just Bayesian ones.
GridSearch and PointEstimateSampler runs also return a populated
chain, with sample_burnin set to None. Fits driven by a conventional
optimizer (CMAES, ScipyMinimize, and friends), along with
optimization and validation jobs, return an empty dict.
An empty dict also comes back when there is no metadata blob to read —
a job that failed before writing one, an unknown job_id, or a job
belonging to another organization all surface as "no samples" rather
than an error. Check that the job exists and completed before reading
an empty result as "this fit produced no chain".
Use client.job.get_posterior_samples for the sample chain alone.
For everything else in the metadata blob — submitted configs,
validation payloads, optimization traces — use
client.job.get_metadata.