REST API patterns for chemistry workflows, from lookups to jobs
Chemistry REST workflows run well on stable identifiers as keys, cached lookups, batched requests, polled jobs, careful retries and raw responses saved to disk.
A chemistry workflow built on a REST API runs well when six patterns are in place. Key every request and every cached result by a stable identifier. Cache lookups, which are free and repeatable. Batch and paginate rather than hammer. Treat anything that computes as a job you submit and poll. Retry only the failures that can succeed on a second try. Save raw responses before deriving anything from them. This guide explains each pattern with code that does not depend on any particular endpoint, and points to the API documentation for the actual routes and schemas.
Key everything by a stable identifier
Names and free-form SMILES make poor keys. The same molecule has many SMILES strings, and a name can resolve to a salt on one day and the parent compound on another. Resolve each input once, keep the InChIKey or the database accession the service returns, and use that as the key for every later request and every cache entry. The guide on InChI and InChIKey explains why the hashed key is well suited to this role. When a workflow joins results from several services, the InChIKey is the column they share.
Cache lookups, they are free and repeatable
Lookups such as a property profile, a drug record or a target page return the same answer for the same identifier until the underlying data is updated. Cache them on disk, keyed by identifier plus endpoint plus a version string you bump when the service announces a change. A workflow that profiles ten thousand compounds and is rerun after a small fix should hit the network for none of them. Caching also respects rate limits, which exist on free lookups, and it leaves an audit trail of exactly what the service returned on a given date.
import json, hashlib, pathlib
CACHE = pathlib.Path("cache")
def cached_get(session, url, key):
"""Return a JSON response from disk if present, else fetch and store it."""
CACHE.mkdir(exist_ok=True)
path = CACHE / (hashlib.sha256(key.encode()).hexdigest() + ".json")
if path.exists():
return json.loads(path.read_text())
response = session.get(url, timeout=30)
response.raise_for_status()
path.write_text(response.text)
return response.json()
The url comes from the documentation. The key is the identifier, endpoint and version, so a cache hit never depends on how a URL happened to be formatted.
Batch and paginate
When an endpoint accepts several identifiers in one call, send them in chunks of the size the documentation allows, not one at a time and not all at once. When a search returns pages, follow the pagination the service provides and stop when it says there are no more, rather than guessing a page count. Both habits reduce request counts, which is what rate limits measure, and both make a run restartable, because the chunk or page number tells you where to resume.
Long jobs, submit then poll
Docking, molecular dynamics and QSAR training take longer than an HTTP request should stay open. The pattern is to submit, receive a job identifier, store it, and poll the status with exponential backoff and jitter. Start at a few seconds, double on each check, cap at about a minute, and add a random fraction so that many clients do not poll in step. When the job is done, fetch the result once and write it to disk under the job identifier. A restart then finds the file and does not resubmit, which matters when the job costs credits. The guide on credits and cost control covers the budgeting side.
import random, time
def wait_for(check_status, first=3.0, cap=60.0, limit=3600.0):
"""Poll check_status() with exponential backoff until it returns a result."""
delay, waited = first, 0.0
while waited < limit:
result = check_status()
if result is not None:
return result
sleep = delay + random.uniform(0, delay / 2)
time.sleep(sleep)
waited += sleep
delay = min(delay * 2, cap)
raise TimeoutError("job did not finish in time")
Fail loudly, retry carefully
Two classes of failure need different handling. A 429 or a 5xx response means the service was busy or briefly broken, and a retry after a pause often succeeds. Respect a Retry-After header if there is one. A 4xx response other than 429 means the request itself was wrong, an unparsable SMILES or an unknown identifier, and it will fail again. Log it with the request identifier from the response and move on. Never swallow an error and write an empty row, because an empty row looks like a negative result to the next person who reads the file.
Save raw responses, then derive
Write the response body to disk before parsing it, and let every downstream table be rebuilt from those files. The raw file is the evidence of what the service said. The derived table is your interpretation of it. When a definition changes, for example a descriptor is renamed, you re-derive without re-fetching. The guide on reproducible cheminformatics notebooks applies the same separation inside a notebook, and the two habits together make a run that can be audited a year later.
Choosing between the REST API and MCP
The REST API suits scripts, pipelines and anything scheduled. It gives you exact control over batching, caching and retries. The MCP server suits exploration inside an AI assistant, where a person asks questions in prose and the assistant chooses the tool. The guide on using MolForge from an AI assistant covers that path. Many teams use both, with the assistant for the first afternoon and the API for the run that follows. In either case lookups are free within rate limits, paid tools state their credit price before running, and the documentation is the source of truth for routes, parameters and response fields.
Key points
- Key requests and cache entries by InChIKey or accession plus endpoint and version, never by name or raw SMILES.
- Cache free lookups on disk so reruns touch the network only for new compounds.
- Send batches of the documented size and follow server pagination.
- Treat computations as jobs. Submit, store the identifier, poll with backoff and jitter, save the result once.
- Retry 429 and 5xx with backoff, do not retry other 4xx, and keep raw responses before deriving anything.
Questions people ask
- What should be the key when caching chemistry API responses?
- A stable identifier such as the InChIKey or a database accession, combined with the endpoint name and its version. Names and raw SMILES make poor keys because the same molecule can be written many ways and a name can resolve to a salt or a parent on different days.
- How should a script wait for a long-running computational job?
- Submit the job, store the identifier it returns, then poll its status with exponential backoff and a little random jitter, starting at a few seconds and capping at a minute or so. Never poll in a tight loop. Store the final result to disk under the job identifier so a restart does not resubmit.
- Which HTTP errors should a chemistry client retry?
- Retry 429 and most 5xx responses with backoff, respecting any Retry-After header. Do not retry 4xx responses other than 429, because a malformed SMILES or an unknown identifier will fail the same way every time. Log the request identifier from the response with every failure.
Further reading
In practice: Everything on MolForge is reachable from the browser, the REST API and the MCP server. Lookups are free; a paid tool shows its price in credits before it runs.