@biolibs/entrez
v1.1.1
Published
NCBI E-utilities client, verified against Biopython: efetch, esearch, esummary, elink, epost, einfo, espell and ecitmatch build the same requests, with the same rate limit and retries, and read and parse turn the XML that comes back into lists and diction
Maintainers
Readme
@biolibs/entrez
A client for NCBI's E-utilities — GenBank, PubMed, Protein, Taxonomy and the rest of Entrez — that sends
the requests Biopython's Bio.Entrez sends, and reads the XML that comes back the way Entrez.read and
Entrez.parse read it. It is the one @biolibs package that touches the network.
- The eight E-utilities —
efetch,esearch,esummary,elink,epost,einfo,espell,ecitmatch, with Biopython's names and arguments - The same request, byte for byte — the same parameter order, the same URL encoding, the same switch from GET to POST for long queries and long identifier lists
- The same manners — at most three requests a second, ten with an API key; retries for server errors and dropped connections, none for a plain "not found"
- Runs in a browser — NCBI's servers answer with
Access-Control-Allow-Origin: *, so a page can fetch a record with no server of its own - One replaceable function touches the network — swap
settings.transportto route requests through a proxy, add caching, or test without a connection - The XML read back —
readandparseturn a reply into lists, dictionaries, strings and integers, deciding which is which from the DTD the reply names, as Biopython does - Every DTD Biopython ships, 291 of them, inside the package: nothing is downloaded to read a reply
- Two dependencies,
@biolibs/coreand@biolibs/seqio, whose XML scanner this builds on
Sequence records come back as text for @biolibs/seqio; XML comes back as bytes for read.
What is verified
A generator drives the real Biopython with its network call replaced, and records what it would have sent: the method, the full URL, the POST body, the warning it gives when no email address is set, and the exception type and message where it raises. The tests replay those recordings.
| Upstream module | Items at parity | Checklist |
|---|---|---|
| Bio.Entrez | 10 / 10 | Bio.Entrez.md |
| Bio.Entrez.Parser | 53 / 53 | Bio.Entrez.Parser.md |
The requests: 1,092 recorded cases against Biopython 1.88.
| Cases | What they record |
|---|---|
| 210 | the eight public functions, each under five combinations of email, tool and API key |
| 240 | _build_request: every class of character in a query, lists, numbers, bytes, the GET/POST switch either side of both its limits |
| 160 | _construct_params: what is added, what is dropped, and when it warns |
| 237 | _has_api_key |
| 206 | _open: the pause between requests, which errors are retried and how often, and the reply |
| 24 | _format_ids |
| 15 | _update_ecitmatch_variables |
Reading the replies: 1,791 recorded cases of read and parse, and under them 2,100 cases of
the XML parser they stand on.
| Cases | What they record |
|---|---|
| 164 | a reply of each kind — esearch, esummary, einfo, elink, epost, espell, egquery, a PubMed article set with MathML, a taxonomy set, a JATS article, an XML Schema report — under every combination of validate, escape and ignore_errors |
| 516 | what is not a good reply: not XML, no DTD, a DTD from somewhere it should not come from, a DTD that is not shipped, tags the DTD lacks, errors NCBI reports in the XML, malformed eSummary items, namespaces |
| 1,019 | good replies broken one character at a time, or cut short |
| 92 | long replies for parse, which reads 1,024 bytes at a time: which records are yielded before a late fault |
| 291 | every DTD Biopython ships: what elementDecl decides each of its elements is |
| 2,100 | the XML parser: every handler call real expat makes, in order, for documents and DTDs of every shape — 1,897 of them DTDs broken one character at a time, with the error and the line and column expat gives |
| 291 | every shipped DTD again, through the XML parser: each element, attribute and entity declaration |
Each case holds every element Biopython built — its tag, attributes, key and the tags it allows — and the
repr of the whole, or the exception with its message. For parse, the records it yielded before
failing are part of the answer.
Where the claim stops:
- Nothing is downloaded while parsing. Biopython fetches a DTD it does not have.
readis not asynchronous and cannot, so a reply naming a DTD that is not among the 291 fails as Biopython fails with no network:RuntimeError: Failed to access …. Fetch it yourself andregisterDtdit. - Expat is stood in for, not ported. Python's parser is expat, a C library. The stand-in is held to
the 2,100 recorded cases, which cover what Biopython uses of it. Two things it does not do: follow a
reference to an external general entity (NCBI's DTDs have none), and model expat's input buffer for
anything but
parse's 1,024-byte reads. - Text is refused, as in Python.
readtakes bytes or a handle. A string raisesStreamModeError: XML names its own encoding, and a string has already been decoded by someone who did not ask it. - One order is chosen where Python's is random. A dictionary element starts with an empty list for
each tag that may repeat, and Biopython makes them by walking a
frozenset— so their order changes from one Python process to the next. Here they are alphabetical. Every other key is in document order. - DTD names are matched exactly. On a Mac Biopython finds
eLink_101123.dtdunder any capitals, because the file system does; on Linux it does not. This follows Linux. - The network itself is not recorded.
fetchTransport, the default way of sending a request, is tested against a stand-in forfetch, not against Biopython: there is nothing reproducible to record. Everything up to the moment of sending, and everything done with the reply, is. - A reply is read in full before it is returned. Biopython hands back an open connection to read from; this hands back the bytes. For the size of reply the E-utilities give, the difference is memory, not behaviour.
- Whole numbers and other numbers are one type here.
5is written as Python writes theint5. There is no way to pass thefloat5.0, which Python would write as5.0; pass the text"5.0".
Oddities that are Biopython's and are kept:
elinkwith a number foridraisesAttributeError: 'int' object has no attribute 'count'. It does not join its identifiers, and then asks the number how many commas it has.- With
maxTriesset to 0 nothing is sent, and the result isUnboundLocalError. - A server error is retried at once; only a connection that got no answer waits
sleepBetweenTries.
Install
npm install @biolibs/entrez- ESM only, Node 20 or later, TypeScript declarations included
- Uses the platform's
fetch: every current browser, and Node 20 or later
graph BT
entrez["@biolibs/entrez"] --> core["@biolibs/core<br/><i>Python errors, warnings, UTF-8, inflate</i>"]
entrez --> seqio["@biolibs/seqio<br/><i>the XML scanner; sequence text is for it too</i>"]Say who you are
NCBI asks every client to give an email address, so that it can get in touch before blocking heavy use. Set it once. Biopython warns on every request made without one, and so does this.
import { settings } from "@biolibs/entrez";
settings.email = "[email protected]"; // Python: Entrez.email = "[email protected]"
settings.tool; // "biopython" — sent as-is unless you change it
settings.apiKey = "0123456789abcdef"; // optional: raises the limit from 3 requests a second to 10Your email address is sent to NCBI with every request, in the URL. That is what NCBI asks for, and what Biopython does; it is worth knowing before using this in a page other people will open.
Fetching a record
efetch takes the database and then the rest of the parameters as an object, where Python takes
keyword arguments.
import { efetch } from "@biolibs/entrez";
import { read } from "@biolibs/seqio";
const handle = await efetch("nucleotide", { id: "EU490707", rettype: "gb", retmode: "text" });
handle.url; // the address the reply came from
handle.text; // true — NCBI declared it plain text
const record = read(handle.readText(), "genbank");
record.id; // "EU490707.1"handle.read() does what Python's does: text for a plain-text reply, bytes for anything else, which is
how XML arrives. handle.readText() always gives text, and handle.bytes always gives the bytes.
Searching
import { esearch } from "@biolibs/entrez";
const handle = await esearch("nucleotide", "Opuntia[orgn] AND rpl16", { retmax: 5, idtype: "acc" });
handle.readText(); // XML listing the matching identifiersThe reply is XML, and read makes sense of it.
Reading the XML back
read is Biopython's Entrez.read. Give it the handle, or the bytes:
import { type DictionaryElement, type ListElement, esearch, read } from "@biolibs/entrez";
const handle = await esearch("pubmed", "biopython[title]", { retmax: 3 });
const record = read(handle) as DictionaryElement;
record.get("Count")?.toString(); // "3"
(record.get("IdList") as ListElement).map(String); // ["19304878", "18606172", "16403221"]
record.repr();
// "{'Count': '3', 'RetMax': '3', 'RetStart': '0', 'IdList': ['19304878', '18606172', '16403221']}"What comes back is ordinary data — a dictionary is a Map, a list is an Array, a string is a String
— and each piece also remembers the element it came from:
const ids = record.get("IdList") as ListElement;
ids.tag; // "IdList"
ids[0]!.tag; // "Id"
ids[0]!.attributes; // Map(0) {}Which element is a list and which a dictionary is not in the XML. It is in the DTD the reply names, and
the package carries every DTD Biopython does. repr() gives what Python would print.
parse is Entrez.parse, for a reply that is a list of records. It yields them one at a time:
import { type DictionaryElement, efetch, parse } from "@biolibs/entrez";
const handle = await efetch("taxonomy", { id: "9615,9685", retmode: "xml" });
const names: string[] = [];
for (const record of parse(handle)) names.push(String((record as DictionaryElement).get("ScientificName")));
names; // ["Canis lupus familiaris", "Felis catus"]Both take Biopython's three options, as an object:
read(handle, { validate: false }); // skip tags the DTD does not define, instead of ValidationError
read(handle, { escape: true }); // & < > in text become & < >
read(handle, { ignoreErrors: true }); // keep an <ERROR> from NCBI as an ErrorElement, instead of RuntimeErrorA reply that names a DTD the package does not have cannot be read until you supply it:
import { read, registerDtd } from "@biolibs/entrez";
registerDtd("mine.dtd", "<!ELEMENT Result (Id*)> <!ELEMENT Id (#PCDATA)>");
const xml = '<?xml version="1.0"?><!DOCTYPE Result SYSTEM "https://www.ncbi.nlm.nih.gov/dtd/mine.dtd"><Result><Id>1</Id><Id>2</Id></Result>';
read(new TextEncoder().encode(xml)).repr(); // "['1', '2']"Only a DTD at https://…nlm.nih.gov/ is accepted, as in Biopython 1.88: a reply with an http://
DOCTYPE, which older saved replies have, is refused with ValueError: Expected secure URL to NCBI.
The request, without sending it
buildRequest is Biopython's _build_request: it returns what would be sent.
import { EUTILS, buildRequest, settings } from "@biolibs/entrez";
settings.email = "[email protected]";
const request = buildRequest(`${EUTILS}esearch.fcgi`, { db: "pubmed", term: "biopython[title]", retmax: 20 });
request.method; // "GET"
request.fullUrl;
// "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=biopython%5Btitle%5D&retmax=20&tool=biopython&email=a.n.other%40example.com"It switches to POST by itself when the encoded parameters come to more than 1,000 characters, or when there are 200 or more identifiers, whichever happens first:
const ids = Array.from({ length: 200 }, (_, i) => 1000 + i);
const big = buildRequest(`${EUTILS}efetch.fcgi`, { db: "nucleotide", id: ids });
big.method; // "POST"
big.fullUrl; // ".../efetch.fcgi" — the parameters are in the body
new TextDecoder().decode(big.data!).slice(0, 30); // "db=nucleotide&id=1000%2C1001%2"
buildRequest(`${EUTILS}efetch.fcgi`, { db: "nucleotide", id: ids.slice(0, 50) }).method; // "GET"Identifiers
A list of identifiers is joined with commas, and text is tidied, by formatIds:
import { formatIds } from "@biolibs/entrez";
formatIds(19304878); // "19304878"
formatIds(" 1 , 2 ,3 "); // "1,2,3"
formatIds(["EU490707", 19304878]); // "EU490707,19304878"elink is the exception. It repeats id once per identifier, which asks NCBI for each one's links
separately:
import { EUTILS, buildRequest } from "@biolibs/entrez";
// What elink sends for a list: joinIds is false.
buildRequest(`${EUTILS}elink.fcgi`, { dbfrom: "protein", db: "gene", id: ["15718680", "157427902"] }, null, false, false).fullUrl;
// ".../elink.fcgi?dbfrom=protein&db=gene&id=15718680&id=157427902&tool=biopython&email=a.n.other%40example.com"URL encoding
Python's urlencode is not encodeURIComponent, and the differences change the bytes sent.
quotePlus and urlencode are exported for anything else that has to match it.
import { quotePlus, urlencode } from "@biolibs/entrez";
quotePlus("Opuntia[orgn] AND rpl16"); // "Opuntia%5Borgn%5D+AND+rpl16" — a space is +
quotePlus("it's (here)!*~"); // "it%27s+%28here%29%21%2A~" — only ~ survives
quotePlus("日本"); // "%E6%97%A5%E6%9C%AC"
urlencode(new Map<string, unknown>([["id", [1, 2]], ["usehistory", true], ["retmax", null]]));
// "id=1&id=2&usehistory=True&retmax=None"Pacing and retries
Requests are kept at least 0.37 seconds apart, or 0.1 with an API key. A reply that is a server error
or "too many requests" is asked for again at once; a connection that gets no answer is retried after
sleepBetweenTries seconds; any other 4xx is final.
import { HTTPError, settings } from "@biolibs/entrez";
settings.maxTries; // 3
settings.sleepBetweenTries; // 15 — seconds
try {
await efetch("nucleotide", { id: "EU490707", rettype: "gb", retmode: "text" });
} catch (error) {
if (error instanceof HTTPError) {
error.code; // the HTTP status, such as 429
error.message; // "HTTP Error 429: Too Many Requests"
}
}An identifier NCBI does not know is not an HTTP error: the reply has status 200 and says what was wrong in its body. Check what came back.
Replacing the network
Everything is sent through settings.transport. Replace it to add a cache, go through your own server,
or run with no connection at all. It is given the request and returns the reply, or throws HTTPError
or URLError.
import { efetch, settings, type Transport } from "@biolibs/entrez";
const canned: Transport = async (request) => ({
url: request.fullUrl,
contentType: "text/plain",
body: new TextEncoder().encode(">made-up record\nACGT\n"),
});
settings.transport = canned;
const handle = await efetch("nucleotide", { id: "anything", rettype: "fasta", retmode: "text" });
handle.readText(); // ">made-up record\nACGT\n"settings.now and settings.sleep are the clock and the wait, replaceable the same way, which is how
the tests run 206 cases of pacing and retrying in a few milliseconds.
The other E-utilities
| Python | TypeScript | Notes |
|---|---|---|
| Entrez.efetch(db, **kw) | efetch(db, kw?) | records, in the format rettype and retmode ask for |
| Entrez.esearch(db, term, **kw) | esearch(db, term, kw?) | identifiers matching a query |
| Entrez.esummary(**kw) | esummary(kw?) | document summaries |
| Entrez.elink(**kw) | elink(kw?) | related records; repeats id instead of joining it |
| Entrez.epost(db, **kw) | epost(db, kw?) | upload identifiers to the history server; always a POST |
| Entrez.einfo(**kw) | einfo(kw?) | the databases, or one database's fields |
| Entrez.espell(**kw) | espell(kw?) | spelling suggestions |
| Entrez.ecitmatch(**kw) | ecitmatch(kw?) | PubMed identifiers for citations |
| Entrez.email, tool, api_key | settings.email, tool, apiKey | |
| Entrez.max_tries, sleep_between_tries | settings.maxTries, sleepBetweenTries | |
| Entrez.read(source, validate, escape, ignore_errors) | read(source, { validate, escape, ignoreErrors }) | not a promise: the reply is already in hand |
| Entrez.parse(source, …) | parse(source, { … }) | a generator |
Each E-utility returns a promise. The request is built before the function returns, so a bad argument throws straight away, not when the promise is awaited.
Testing
npm test # the whole workspace
npx vitest run packages/entrez/test| File | What it checks |
|---|---|
| test/entrez.test.ts | the 1,092 recorded requests from Biopython 1.88 |
| test/entrez-parser.test.ts | the 1,791 recorded cases of read and parse, and elementDecl on all 291 DTDs |
| test/expat.test.ts | the 2,100 recorded cases of the XML parser against real expat, and all 291 DTDs through it |
| test/transport.test.ts | fetchTransport, against a stand-in for fetch |
| test/readme.test.ts | every code block in this file |
No test touches the network.
Things to know
- A browser cannot set a
User-Agent, and does not need to: NCBI identifies clients by thetoolandemailparameters, which is what is sent. - Key order is the order sent. Parameters go out in the order you wrote them, then
tool,emailandapi_key. JavaScript moves object keys that look like whole numbers to the front; if you have one, pass aMapor an array of pairs instead of an object. nullandundefinedmean "leave it out", asNonedoes in Python. Passingemail: nulldrops the email for that request, and brings the warning back.- Rate limiting is per page or process. Two tabs, or two programs, each keep their own count.
License
MIT — see LICENSE.
