All connectors
PubMed
Official
PubMed
Let agents search biomedical literature, read abstracts, authors and MeSH terms, follow citations and retrieve eligible PMC full text. Access is read-only and requires no account; an optional NCBI key provides a higher quota.
Abstracts may be copyrighted and PMC articles have individual licences. Follow the rights holder's terms and NCBI's notice.
This connector is not affiliated with the National Library of Medicine or NCBI.
Setup instructions
Setup instructions
Add PubMed
- Add PubMed in Houston. No account is required.
- Optionally enter NCBI API key for a higher request quota, then select Add connection.
Advanced
Create a free key under NCBI account settings → API Key Management. Paste it into Houston's NCBI API key. Creating a replacement invalidates the previous key; update every connection using it.
Full text is available only for eligible PMC articles. Broad searches are limited to 9,999 matches; narrow by date or topic.
Files
Files
connector.luau
-- NCBI E-utilities for PubMed and the BioC API for PMC open-access full text, public and read-only. Arguments and results keep NCBI's native field names. type Options = {[string]: any} local EUTILS = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/" local BIOC = "https://www.ncbi.nlm.nih.gov/research/bionlp/RESTful/pmcoa.cgi/BioC_json/" -- NCBI asks each request to name the software and its developer's contact address, never an end user's. local CONTACT = "tool=houston&email=" .. url.encode("[email protected]") -- Each call makes one request. Houston ends a call after 30 s and the sandbox has no clock, so a fixed split of -- 27 s gives the response body, an error body included, 19 s and the headers the rest. NCBI sends headers within -- 0.3 s and then streams the body: 1.7 s for 200 MEDLINE records, 0.1 s per PMID for ELink, which gives up after -- about 15 s with an empty 200; the 8 s for headers leave room for Houston's two short waits after an HTTP 429. local CALL_TIME, BODY_TIME = 27000, 19000 local MAX_BYTES = 4 * 1024 * 1024 local MAX_IDS, MAX_LINK_IDS, MAX_TERM, DEFAULT_RETMAX = 200, 100, 4000, 20 -- PubMed returns only the first 9,999 matches of a search. local MAX_RESULTS = 9999 local SORTS = table.freeze({"relevance", "pub_date", "Author", "JournalName"}) local DATETYPES = table.freeze({"edat", "pdat", "mdat"}) -- Link names to PubMed and PMC records, in help order, with what each returns. local LINKS = table.freeze({ {"pubmed_pubmed", "similar articles, most similar first; the list can include the article itself"}, {"pubmed_pubmed_reviews", "similar review articles"}, {"pubmed_pubmed_citedin", "PubMed articles citing it, from reference lists deposited in PMC, highest PMID (newest) first"}, {"pubmed_pubmed_refs", "the PubMed articles it cites, when its reference list is in PMC"}, {"pubmed_pmc", "its PMC copy, as a PMC number without the PMC prefix (getFullText takes \"PMC\" .. number)"}, {"pubmed_pmc_refs", "PMC articles citing it, as PMC numbers"}, }) local LINK_NAMES: {[string]: boolean}, linkNames: {string} = {}, {} for _, link in LINKS do LINK_NAMES[link[1]] = true table.insert(linkNames, link[1]) end local LINK_LIST = table.concat(linkNames, ", ") -- MEDLINE tags that occur at most once per record come back as strings; every other tag is an array of strings. local SINGLE_TAGS = "PMID OWN STAT DCOM LR VI IP DP TI BTI VTI TT PG AB CI JT TA JID PL EDAT MHDA CRDT PST SO PMC DEP" local SINGLE: {[string]: boolean} = {} for tag in string.gmatch(SINGLE_TAGS, "%S+") do SINGLE[tag] = true end -- Author tags: FAU, AU or CN (a corporate author) starts an author, and AUID and AD describe the one before them. local AUTHOR = table.freeze({FAU = true, AU = true, CN = true, AUID = true, AD = true}) local function finite(value: any): boolean return type(value) == "number" and value == value and math.abs(value) < 2 ^ 53 end local function integer(value: any, field: string, minimum: number, maximum: number): number assert(finite(value) and value % 1 == 0 and value >= minimum and value <= maximum, field .. " must be an integer from " .. tostring(minimum) .. " to " .. tostring(maximum)) return value end local function choice(value: any, field: string, values: {string}): string assert(type(value) == "string" and table.find(values, value), field .. " must be one of " .. table.concat(values, ", ")) return value end local function options(value: any, operation: string): Options assert(value == nil or type(value) == "table", operation .. " options must be a table") return table.clone((value or {}) :: Options) end local function noneLeft(args: Options, operation: string) local unknown = next(args) assert(unknown == nil, operation .. " received an unknown option " .. string.sub(tostring(unknown), 1, 64)) end -- A PMID is a positive integer of at most 9 digits, given as a number or a string. local function pmid(value: any): string? local id = if finite(value) and value % 1 == 0 then string.format("%d", value) elseif type(value) == "string" then value else "" return if #id <= 9 and string.match(id, "^[1-9]%d*$") then id else nil end -- Takes one PMID, an array of them or one string separated by commas or spaces; drops repeats and keeps the order. local function pmids(value: any, maximum: number): {string} local items: {any} = {} if type(value) == "string" then for item in string.gmatch(value, "[^,%s]+") do table.insert(items, item) end elseif type(value) == "table" then for index, item in value do assert(index == #items + 1, "ids must be a dense array") table.insert(items, item) end else items = {value} end local out: {string}, seen: {[string]: boolean} = {}, {} for _, item in items do local id = pmid(item) assert(id, "ids must contain PMIDs, positive integers such as 31452104") if not seen[id] then seen[id] = true table.insert(out, id) end end assert(#out > 0 and #out <= maximum, "ids must list 1 to " .. tostring(maximum) .. " PMIDs") return out end local function errorCode(err: any): any return if type(err) == "table" then err.code else nil end local function fail(operation: string, status: number?, retryable: boolean, message: string): never return houston.fail({operation = operation, layer = "upstream", upstream_status = status, retryable = retryable, message = message}) end -- NCBI reports errors as JSON in several shapes, or as XML from efetch. local function reported(value: any): string? if type(value) ~= "table" then return nil end local message = value.error or value.ERROR or (type(value.esearchresult) == "table" and value.esearchresult.ERROR) or (type(value.esummaryresult) == "table" and value.esummaryresult[1]) return if type(message) == "string" then message else nil end -- houston.fail repairs a character split by the cut. local function tidy(message: string): string return string.sub(string.match(string.gsub(message, "%s+", " "), "^ ?(.-) ?$") :: string, 1, 300) end -- Phrases of NCBI's messages about input it rejects, which retrying cannot fix, even inside a successful answer. local REJECTIONS = table.freeze({"invalid", "too many", "cannot be larger", "empty term", "nothing todo", "not wellformed"}) -- Fails with an error NCBI reported in a 200 answer: a rejection is final, any other failure, such as -- "Search Backend failed", a server fault. local function reportedFailure(operation: string, message: string): never local lower = string.lower(message) local rejected = false for _, phrase in REJECTIONS do rejected = rejected or string.find(lower, phrase, 1, true) ~= nil end return fail(operation, 200, not rejected, "NCBI: " .. tidy(message)) end local function reason(body: string): string local message if string.match(body, "^%s*{") then local ok, decoded = pcall(json.decode, body) message = if ok then reported(decoded) else nil else message = string.match(body, "<ERROR>(.-)</ERROR>") end return if message then tidy(message) else "" end local function failure(operation: string, response: HttpResponse): never local status = response.statusCode local detail = "" if status >= 300 and status < 400 then response.body:close() detail = "unexpected redirect" else -- An error body that stalls or breaks counts as empty; HTML pages are never shown. local read, prefix = pcall(function() return await(response.body:readPrefix(4096), BODY_TIME) end) if not read and errorCode(prefix) == "cancelled" then error(prefix, 0) end if read then detail = reason(prefix) end end local message = "NCBI HTTP " .. tostring(status) .. (if detail == "" then "" else ": " .. detail) local retry = response.headers["retry-after"] if (status == 429 or status == 503) and retry and retry[1] then -- Retry-After is either delay seconds or an HTTP date. local value = string.sub(retry[1], 1, 32) message ..= "; retry after " .. value .. (if string.match(value, "^%d+$") then "s" else "") end -- Input is validated first, so NCBI's 4xx answers are final and its 5xx answers are server faults. return fail(operation, status, status == 429 or status >= 500, message) end -- Returns the body of a 200 response and its headers; tooMuch tells the caller how to fit the byte budget. local function fetch(operation: string, request: Options, tooMuch: string): (string, {[string]: {string}}) request.timeoutMs = CALL_TIME - BODY_TIME local sent, response = pcall(function() return await(http.request(request :: any)) end) if not sent then if errorCode(response) ~= "timeout" then error(response, 0) end fail(operation, nil, true, "NCBI did not answer within " .. tostring((CALL_TIME - BODY_TIME) // 1000) .. " s; retry") end if response.statusCode ~= 200 then failure(operation, response) end local read, raw = pcall(function() return await(response.body:readAll(MAX_BYTES), BODY_TIME) end) if not read then local code = errorCode(raw) if code == "limit_exceeded" then fail(operation, 200, false, "NCBI returned more data than one call can hold; " .. tooMuch) elseif code == "timeout" then fail(operation, 200, true, "NCBI did not finish sending its answer within " .. tostring(BODY_TIME // 1000) .. " s; retry") elseif code == "cancelled" then error(raw, 0) end local detail = if type(raw) == "table" and type(raw.message) == "string" then raw.message else tostring(raw) fail(operation, 200, true, "NCBI response failed: " .. string.sub(detail, 1, 300)) end return raw, response.headers end -- Calls one E-utility, posted as a form so long ID lists and queries fit. local function eutility(operation: string, name: string, params: {string}, tooMuch: string): string return (fetch(operation, {method = "POST", url = EUTILS .. name .. ".fcgi", headers = {["Content-Type"] = {"application/x-www-form-urlencoded"}}, body = table.concat(params, "&") .. "&" .. CONTACT}, tooMuch)) end local function decode(operation: string, raw: string, key: string): any -- ELink gives up after about 15 s and still answers 200, with an empty body. if not string.find(raw, "%S") then fail(operation, 200, true, "NCBI returned an empty answer; retry, or pass fewer ids") end -- The anchored check is cheap, so a large page that is not JSON is never decoded. local ok, value = false, nil if string.match(raw, "^%s*{") then ok, value = pcall(json.decode, raw) end if not ok or type(value) ~= "table" then fail(operation, 200, false, "NCBI returned an invalid JSON object") end local message = reported(value) if message then reportedFailure(operation, message) end if type(value[key]) ~= "table" then fail(operation, 200, false, "NCBI returned an unexpected answer") end return value[key] end local DAYS = table.freeze({31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}) -- Checks a YYYY, YYYY/MM or YYYY/MM/DD date, which NCBI would otherwise answer with no matches, and returns the -- first and last day it covers as comparable YYYY/MM/DD strings. local function dateRange(value: any, field: string): (string, string) local y: any, m: any, d: any if type(value) == "string" then y = string.match(value, "^(%d%d%d%d)$") if not y then y, m = string.match(value, "^(%d%d%d%d)/(%d%d)$") end if not y then y, m, d = string.match(value, "^(%d%d%d%d)/(%d%d)/(%d%d)$") end end local year: any, month: any, day: any = tonumber(y), tonumber(m), tonumber(d) local leap = year and year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0) local days = if month and month >= 1 and month <= 12 then DAYS[month] + (if month == 2 and leap then 1 else 0) else nil assert(year and year >= 1 and (m == nil or days) and (d == nil or (day >= 1 and day <= days)), field .. " must be YYYY, YYYY/MM or YYYY/MM/DD") return string.format("%04d/%02d/%02d", year, month or 1, day or 1), string.format("%04d/%02d/%02d", year, month or 12, day or days or 31) end local function searchArticles(input: Options?): any local args = options(input, "searchArticles") local term = args.term assert(type(term) == "string" and string.find(term, "%S") and #term <= MAX_TERM, "term must be a PubMed query of at most " .. tostring(MAX_TERM) .. " bytes, not only spaces") local params = {"db=pubmed", "retmode=json", "term=" .. url.encode(term), "retstart=" .. tostring(integer(if args.retstart == nil then 0 else args.retstart, "retstart", 0, MAX_RESULTS - 1)), "retmax=" .. tostring(integer(if args.retmax == nil then DEFAULT_RETMAX else args.retmax, "retmax", 0, MAX_RESULTS))} if args.sort ~= nil then table.insert(params, "sort=" .. choice(args.sort, "sort", SORTS)) end assert((args.mindate == nil) == (args.maxdate == nil), "mindate and maxdate go together") if args.mindate ~= nil then local from = dateRange(args.mindate, "mindate") local _, to = dateRange(args.maxdate, "maxdate") assert(from <= to, "mindate must not be after maxdate") table.insert(params, "mindate=" .. url.encode(args.mindate)) table.insert(params, "maxdate=" .. url.encode(args.maxdate)) end if args.reldate ~= nil then table.insert(params, "reldate=" .. tostring(integer(args.reldate, "reldate", 1, 100000))) end if args.datetype ~= nil then assert(args.mindate ~= nil or args.reldate ~= nil, "datetype applies only with mindate and maxdate, or reldate") table.insert(params, "datetype=" .. choice(args.datetype, "datetype", DATETYPES)) end for _, field in {"term", "retstart", "retmax", "sort", "mindate", "maxdate", "reldate", "datetype"} do args[field] = nil end noneLeft(args, "searchArticles") return decode("searchArticles", eutility("searchArticles", "esearch", params, "lower retmax"), "esearchresult") end local function idParam(ids: any): string return "id=" .. url.encode(table.concat(pmids(ids, MAX_IDS), ",")) end local function getSummaries(ids: any): any return decode("getSummaries", eutility("getSummaries", "esummary", {"db=pubmed", "retmode=json", idParam(ids)}, "request fewer IDs"), "result") end -- A tagged value and its trimmed lines, joined with single spaces as Biopython joins them. type Field = {tag: string, lines: {string}} local function trim(text: string): string return string.match(text, "^%s*(.-)%s*$") :: string end -- Groups a record's tagged values: authors in order, single tags as strings, other tags as arrays. local function record(fields: {Field}): Options local out: Options = {} local authors: {Options} = {} local author: Options? = nil for _, field in fields do local tag, value = field.tag, table.concat(field.lines, " ") if tag == "FAU" or tag == "CN" or (tag == "AU" and (author == nil or author.AU ~= nil or author.CN ~= nil)) then author = {} table.insert(authors, author :: Options) end local target: Options = if AUTHOR[tag] and author then author else out if SINGLE[tag] or tag == "FAU" or tag == "AU" or tag == "CN" then if target[tag] == nil then target[tag] = value end elseif target[tag] then table.insert(target[tag], value) else target[tag] = {value} end end out.authors = if #authors > 0 then authors else json.decode("[]") return out end -- Parses MEDLINE text: empty lines separate records, a line is a tag padded to 4 characters, "- " and a value, and -- lines indented by 6 spaces continue the value before them. local function medline(raw: string): {Options} -- An XML answer is an efetch error. if string.match(raw, "^%s*<") then local message = string.match(raw, "<ERROR>(.-)</ERROR>") if message then reportedFailure("getRecords", message) end fail("getRecords", 200, false, "NCBI returned an unexpected MEDLINE answer") end local records = json.decode("[]") local fields: {Field} = {} for _, line in string.split(raw, "\n") do line = string.gsub(line, "\r$", "") if line == "" then if #fields > 0 then table.insert(records, record(fields)) end fields = {} elseif not string.find(line, "%S") then continue elseif string.sub(line, 1, 6) == " " and #fields > 0 then local text = trim(line) if text ~= "" then table.insert(fields[#fields].lines, text) end else local tag = string.match(string.sub(line, 1, 4), "^(%u[%u%d]*) *$") local dash = string.sub(line, 5, 6) -- Other lines, such as NCBI's note about a PMID it cannot serve, are skipped. if tag and (dash == "- " or dash == "-") then local text = trim(string.sub(line, 7)) table.insert(fields, {tag = tag, lines = if text == "" then {} else {text}}) end end end if #fields > 0 then table.insert(records, record(fields)) end for _, entry in records do if type(entry.PMID) ~= "string" then fail("getRecords", 200, false, "NCBI returned a MEDLINE record without a PMID") end end return records end local function getRecords(ids: any): any local raw = eutility("getRecords", "efetch", {"db=pubmed", "rettype=medline", "retmode=text", idParam(ids)}, "request fewer IDs") return {records = medline(raw)} end local function getLinks(ids: any, linkname: any, input: Options?): any local params = {"dbfrom=pubmed", "retmode=json"} for _, id in pmids(ids, MAX_LINK_IDS) do table.insert(params, "id=" .. id) end assert(type(linkname) == "string" and LINK_NAMES[linkname], "linkname must be one of " .. LINK_LIST) table.insert(params, "linkname=" .. linkname) local args = options(input, "getLinks") assert(args.scores == nil or type(args.scores) == "boolean", "scores must be true or false") table.insert(params, "cmd=" .. (if args.scores then "neighbor_score" else "neighbor")) args.scores = nil noneLeft(args, "getLinks") return decode("getLinks", eutility("getLinks", "elink", params, "request fewer IDs"), "linksets") end local function getFullText(value: any): any local id = if type(value) == "string" then string.upper(value) else pmid(value) or "" assert((#id <= 12 and string.match(id, "^PMC[1-9]%d*$")) or pmid(id), "id must be a PMCID such as PMC4412151 or a PMID such as 25977807") local raw, headers = fetch("getFullText", {method = "GET", url = BIOC .. id .. "/unicode"}, "this article's full text is too large for one call") local kind = headers["content-type"] -- Without open-access full text, the service answers 200 with an HTML error page. if not (kind and kind[1] and string.find(kind[1], "json", 1, true)) then if string.find(raw, "No result can be found", 1, true) then fail("getFullText", 200, false, "PMC has no open-access full text for " .. id .. "; only open-access and author manuscript articles have one, so read its abstract with getRecords") end fail("getFullText", 200, false, "NCBI returned an unexpected full-text answer") end local ok, collection = pcall(json.decode, raw) local documents = if ok and type(collection) == "table" and type(collection[1]) == "table" then collection[1].documents else nil local document = if type(documents) == "table" then documents[1] else nil if type(document) ~= "table" or type(document.passages) ~= "table" then fail("getFullText", 200, false, "NCBI returned an unexpected full-text answer") end return document end local function help(): string local links: {string} = {} for _, link in LINKS do table.insert(links, "- " .. link[1] .. ": " .. link[2] .. ".") end return [[PubMed: search and read NLM's database of biomedical literature citations and abstracts through NCBI's E-utilities (https://www.ncbi.nlm.nih.gov/books/NBK25501/), and the open-access full text of PubMed Central (PMC) articles through NCBI's BioC API. No account needed; an optional NCBI API key only raises the rate limit. Read-only. Calls return completed values; do not wrap them in await(). Results keep NCBI's field names and values: numbers such as count come back as strings. Each call makes one NCBI request. Abstracts can be protected by copyright and PMC articles carry their own licenses (see each document's license); NCBI's disclaimer and copyright notice: https://www.ncbi.nlm.nih.gov/About/disclaimer.html. IDs are PMIDs, positive integers such as 31452104, given as a number or a string. ids takes one PMID, an array of up to ]] .. tostring(MAX_IDS) .. [[ (]] .. tostring(MAX_LINK_IDS) .. [[ for getLinks) or one string separated by commas or spaces; repeats are dropped. ## searchArticles({term, retstart?, retmax?, sort?, datetype?, mindate?, maxdate?, reldate?}) ESearch. Returns `{count, retstart, retmax, idlist, querytranslation, translationset, warninglist?, errorlist?}`: count is the number of matches, idlist the PMIDs of this page, querytranslation how PubMed read the query (with MeSH expansion), warninglist and errorlist phrases and fields PubMed ignored. Unknown options are rejected. - term: a query in PubMed syntax, at most ]] .. tostring(MAX_TERM) .. [[ bytes, for example `crispr[tiab] AND review[pt]`, `"Smith J"[au]`, `asthma[majr]`, `Nature[ta] AND 2024[dp]` or `31452104[pmid]`. Tags include [tiab] (title or abstract), [ti], [au], [1au] (first author), [ad] (affiliation), [mh] (MeSH, with subheadings), [majr] (major MeSH topic), [pt] (publication type), [ta] (journal), [dp] (publication date), [la] (language), [ot] (keyword) and [sb] (subset, such as free full text[sb]); combine with AND, OR, NOT and parentheses. - retmax: PMIDs to return, 0 to ]] .. tostring(MAX_RESULTS) .. [[ (default ]] .. tostring(DEFAULT_RETMAX) .. [[; 0 returns only count). retstart: matches to skip, 0 to ]] .. tostring(MAX_RESULTS - 1) .. [[ (default 0). For the next page, call again with retstart + retmax as retstart while that is below both count and ]] .. tostring(MAX_RESULTS) .. [[. PubMed returns only the first ]] .. tostring(MAX_RESULTS) .. [[ matches: retstart plus the PMIDs returned never exceeds ]] .. tostring(MAX_RESULTS) .. [[ (retstart = 9990 with retmax = 20 returns 9), so narrow larger result sets, for example by date. - sort: ]] .. table.concat(SORTS, ", ") .. [[. relevance (PubMed's Best Match) is the default; pub_date sorts newest first, Author and JournalName ascending. - mindate and maxdate together: YYYY, YYYY/MM or YYYY/MM/DD, real dates with mindate not after maxdate (NCBI would answer other dates with no matches). reldate: only the last n days. datetype selects the date they filter: edat (added to PubMed, the default), pdat (publication) or mdat (modification). ## getSummaries(ids) ESummary. Returns `{uids, [pmid] = summary}`: uids lists the PMIDs in order and each summary has uid, title, authors (array of {name, authtype}), lastauthor, source (journal abbreviation), fulljournalname, pubdate, epubdate, volume, issue, pages, elocationid, lang, pubtype, articleids (array of {idtype, value}, idtype pubmed, doi, pmc, pmcid, pii or mid), attributes (such as "Has Abstract"), pmcrefcount and sortpubdate. A summary has no abstract or MeSH terms; use getRecords. An unknown PMID gets `{uid, error = "cannot get document summary"}`. ## getRecords(ids) EFetch in MEDLINE format. Returns `{records}`, one complete record per known PMID in the order given; unknown PMIDs are left out, so the array can be empty. Records use MEDLINE tags as keys. These are strings: ]] .. string.gsub(SINGLE_TAGS, " ", ", ") .. [[; every other tag is an array of strings in record order. authors is always an array of {FAU (full name), AU (short name), AUID? (array, such as "ORCID: 0000-0002-4242-7526"), AD? (array of affiliations)} in author order, where a corporate author is {CN (group name), AD?}. Main tags: PMID; TI title; AB abstract (structured abstracts keep labels such as "BACKGROUND:"); DP publication date; TA journal abbreviation and JT full title; VI, IP and PG volume, issue and pages; LID and AID identifiers such as "10.1136/bmj.n71 [doi]"; PMC the PMCID; MH MeSH headings, where `*` marks a major topic and `/` a subheading, as in "*Molecular Docking Simulation" or "Proteins/chemistry"; OT keywords; PT publication types (such as "Review" or "Retracted Publication"); RN substances; GR grants; LA languages; CIN, EIN and RIN comments, errata and retractions; SO the citation. ## getLinks(ids, linkname, opts?) ELink, one linkset per PMID. Returns an array of `{dbfrom, ids, linksetdbs?}` in the order given, where linksetdbs is `{{dbto, linkname, links}}`, absent when the article has none. links are PMIDs, or PMC numbers for the pubmed_pmc links. opts.scores = true returns links as `{id, score}` objects instead; similar-article links score numerically, other links with an empty string. linkname: ]] .. table.concat(links, "\n") .. [[ A long list, such as the citations of a highly cited article, comes back whole: pass fewer ids if a call holds too much. ELink takes about 0.1 s per PMID and gives up after about 15 s with an empty answer, which fails as retryable: pass fewer ids. ## getFullText(id) PMC open-access full text as one BioC document: `{id, infons, passages}`, where id is the PMCID, infons.license the license (such as "CC BY"), and each passage is `{offset, infons, text}` with infons.section_type (TITLE, ABSTRACT, INTRO, METHODS, RESULTS, DISCUSSION, CONCL, REF, FIG, TABLE and others) and infons.type (front, abstract, paragraph, title_1, ref, fig_caption...). The first passage's infons hold article IDs, keywords and the license text. id is a PMCID such as PMC4412151 or a PMID such as 25977807. Only articles in the PMC open-access subset and author manuscript collection have one; any other fails as not found, so read its abstract with getRecords. Find an article's PMCID with getRecords (PMC tag) or getLinks(ids, "pubmed_pmc"). ## Errors and limits Invalid input fails before any request. NCBI errors come back as upstream errors with the HTTP status and NCBI's message; HTTP 429 and 5xx are retryable, as are failures NCBI reports inside a successful answer (such as "Search Backend failed"), except its rejections of input (messages about invalid or too many values or an empty term). Without an API key, NCBI accepts 3 requests per second from Houston as a whole, and 10 per connection with one; Houston waits and retries a refused request briefly, so prefer fewer calls with more IDs over many small ones. Each call reads at most ]] .. tostring(MAX_BYTES // 1048576) .. [[ MiB and gives NCBI ]] .. tostring(CALL_TIME // 1000) .. [[ s: ]] .. tostring((CALL_TIME - BODY_TIME) // 1000) .. [[ to start answering and ]] .. tostring(BODY_TIME // 1000) .. [[ to send the body; a call that runs out of time fails as retryable. Too much data fails as not retryable: pass fewer ids; a larger full text cannot be read. ## Example Here pubmed is the configured PubMed connection. ```lua local found = pubmed.searchArticles({term = "crispr[tiab] AND review[pt]", sort = "pub_date", retmax = 20, datetype = "pdat", mindate = "2024", maxdate = "2025"}) print(found.count) if #found.idlist == 0 then return end -- ids must list at least one PMID local summaries = pubmed.getSummaries(found.idlist) for _, uid in summaries.uids do print(uid, summaries[uid].title, summaries[uid].source, summaries[uid].pubdate) end local record = pubmed.getRecords(found.idlist[1]).records[1] if record then print(record.TI, record.AB, if record.authors[1] then record.authors[1].FAU else nil) local linkset = pubmed.getLinks(record.PMID, "pubmed_pubmed_citedin")[1] local citingIds = if linkset.linksetdbs then linkset.linksetdbs[1].links else {} print(#citingIds, "citing articles") if record.PMC then local article = pubmed.getFullText(record.PMC) for _, passage in article.passages do if passage.infons.section_type == "METHODS" then print(passage.text) end end end end ```]] end return {searchArticles = searchArticles, getSummaries = getSummaries, getRecords = getRecords, getLinks = getLinks, getFullText = getFullText, help = help}houston.json
{ "schema_version": 2, "name": "PubMed", "files": [ "connector.luau" ], "icon": "icon.svg", "config": { "api_key": { "type": "secret", "label": "NCBI API key", "min_length": 1, "description": "Optional. Without a key, every Houston connection shares NCBI's limit of 3 requests per second; with one, this connection gets 10 per second." } }, "proxy": [ { "if": "{{ isDefined config.api_key }}", "match": { "protocol": "http", "host": [ "eutils.ncbi.nlm.nih.gov" ], "method": [ "POST" ], "path": [ "/entrez/eutils/esearch.fcgi", "/entrez/eutils/esummary.fcgi", "/entrez/eutils/efetch.fcgi", "/entrez/eutils/elink.fcgi" ] }, "action": { "headers": { "remove": [ "Authorization", "Cookie" ] }, "query": { "api_key": "{{config.api_key}}" } } }, { "match": { "protocol": "http", "host": [ "eutils.ncbi.nlm.nih.gov" ], "method": [ "POST" ], "path": [ "/entrez/eutils/esearch.fcgi", "/entrez/eutils/esummary.fcgi", "/entrez/eutils/efetch.fcgi", "/entrez/eutils/elink.fcgi" ] }, "action": { "headers": { "remove": [ "Authorization", "Cookie" ] } } }, { "match": { "protocol": "http", "host": [ "www.ncbi.nlm.nih.gov" ], "method": [ "GET" ], "path": [ "/research/bionlp/RESTful/pmcoa.cgi/BioC_json/{id}/unicode" ] }, "action": { "headers": { "remove": [ "Authorization", "Cookie" ] } } } ] }icon.svg
README.md
--- description: Search PubMed's biomedical literature and read abstracts, authors, MeSH terms, citations and open-access full text. --- # PubMed Let agents search biomedical literature, read abstracts, authors and MeSH terms, follow citations and retrieve eligible PMC full text. Access is read-only and requires no account; an optional NCBI key provides a higher quota. > Abstracts may be copyrighted and PMC articles have individual licences. Follow > the rights holder's terms and [NCBI's notice](https://www.ncbi.nlm.nih.gov/About/disclaimer.html). This connector is not affiliated with the National Library of Medicine or NCBI. [Add PubMed](SETUP.md).SETUP.md
# Add PubMed 1. Add PubMed in Houston. No account is required. 2. Optionally enter **NCBI API key** for a higher request quota, then select **Add connection**. ## Advanced Create a free key under [NCBI account settings](https://account.ncbi.nlm.nih.gov/settings/) → **API Key Management**. Paste it into Houston's **NCBI API key**. Creating a replacement invalidates the previous key; update every connection using it. Full text is available only for eligible PMC articles. Broad searches are limited to 9,999 matches; narrow by date or topic. [PubMed help](https://pubmed.ncbi.nlm.nih.gov/help/).tests
authentication.luau
return { contract = function(m) m.authentication({ { auth = {}, config = {}, endpoint = { "POST", "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi" }, expected = "", header = "Authorization", method = "", publisher = {}, }, }) end, }errors.luau
-- With an API key, which the proxy adds: invalid input never reaches NCBI, and NCBI's errors, slow answers and bad -- bodies map to clear failures. return { scenario = {publisher = {}, config = {api_key = "synthetic-ncbi-key"}, auth_method = "", auth_config = {}}, configure = function() calls = 0 status = 200 payload = "{}" responseHeaders = {} http = {request = function(req) calls += 1 assert(not string.find(req.url .. (req.body or ""), "api_key", 1, true), "the proxy adds the key") -- A table stands for a failure while waiting for headers, such as a timeout or a refused origin. if requestError then error(requestError, 0) end -- A body whose read fails stands in for a dropped connection or a cancelled invocation. local body = if readError then {readAll = function() error(readError, 0) end, readPrefix = function() error(readError, 0) end, close = function() end} else fixture.reader(payload) return fixture.operation({statusCode = status, headers = responseHeaders, body = body}) end} end, run = function(pubmed) local function rejected(fn, expected) local before = calls local ok, err = pcall(fn) assert(not ok and string.find(tostring(err), expected, 1, true), "wrong validation error: " .. tostring(err)) assert(calls == before, "invalid input reached NCBI") end local function search(opts) return function() pubmed.searchArticles(opts) end end rejected(function() pubmed.searchArticles("crispr") end, "searchArticles options must be a table") rejected(search({}), "term must be a PubMed query of at most 4000 bytes") -- NCBI answers a blank term with "Search is temporarily unavailable". rejected(search({term = " \n"}), "not only spaces") rejected(search({term = string.rep("a", 4001)}), "at most 4000 bytes") rejected(search({term = 42}), "term must be a PubMed query") rejected(search({term = "x", query = "y"}), "unknown option query") rejected(search({term = "x", db = "pmc"}), "unknown option db") rejected(search({term = "x", usehistory = "y"}), "unknown option usehistory") for _, value in {-1, 9999, 1.5, "10"} do rejected(search({term = "x", retstart = value}), "retstart must be an integer from 0 to 9998") end for _, value in {-1, 10000, 0.5, false} do rejected(search({term = "x", retmax = value}), "retmax must be an integer from 0 to 9999") end -- NCBI ignores an unknown sort and returns relevance order. for _, value in {"date", "pub+date", "author", 1} do rejected(search({term = "x", sort = value}), "sort must be one of relevance, pub_date, Author, JournalName") end rejected(search({term = "x", mindate = "2024"}), "mindate and maxdate go together") rejected(search({term = "x", maxdate = "2024"}), "mindate and maxdate go together") for _, value in {"2024-01-01", "24", "2024/1", "2024/01/1", 2024} do rejected(search({term = "x", mindate = value, maxdate = "2025"}), "mindate must be YYYY, YYYY/MM or YYYY/MM/DD") end rejected(search({term = "x", mindate = "2024", maxdate = "2025/13/01x"}), "maxdate must be YYYY") -- NCBI answers impossible or reversed dates with no matches rather than an error. for _, value in {"2024/13", "2024/00", "2024/01/00", "2024/01/32", "2024/04/31", "2023/02/29", "1900/02/29", "0000"} do rejected(search({term = "x", mindate = value, maxdate = "2025"}), "mindate must be YYYY, YYYY/MM or YYYY/MM/DD") end rejected(search({term = "x", mindate = "2025", maxdate = "2024/12/31"}), "mindate must not be after maxdate") rejected(search({term = "x", mindate = "2024/06/02", maxdate = "2024/06/01"}), "mindate must not be after maxdate") for _, value in {0, 100001, 1.5, "30"} do rejected(search({term = "x", reldate = value}), "reldate must be an integer from 1 to 100000") end rejected(search({term = "x", datetype = "pdat"}), "datetype applies only with mindate and maxdate, or reldate") rejected(search({term = "x", reldate = 7, datetype = "crdt"}), "datetype must be one of edat, pdat, mdat") for _, ids in {{}, "", ",, ", {"abc"}, {"0"}, {0}, {-5}, {1.5}, {"1234567890"}, {"12a"}, {"01"}, {true}, {[1] = 1, [3] = 3}, {{1}}, "1;2"} do rejected(function() pubmed.getSummaries(ids) end, "ids must") end rejected(function() pubmed.getSummaries() end, "ids must list 1 to 200 PMIDs") rejected(function() pubmed.getFullText() end, "id must be a PMCID") rejected(function() pubmed.getSummaries({[1] = 1, [3] = 3}) end, "ids must be a dense array") rejected(function() pubmed.getSummaries({id = 1}) end, "ids must be a dense array") rejected(function() pubmed.getRecords("12a") end, "ids must contain PMIDs, positive integers such as 31452104") local many = {} for i = 1, 201 do many[i] = i end rejected(function() pubmed.getRecords(many) end, "ids must list 1 to 200 PMIDs") rejected(function() pubmed.getLinks(table.move(many, 1, 101, 1, {}), "pubmed_pubmed") end, "ids must list 1 to 100 PMIDs") rejected(function() pubmed.getLinks(1) end, "linkname must be one of pubmed_pubmed, pubmed_pubmed_reviews, " .. "pubmed_pubmed_citedin, pubmed_pubmed_refs, pubmed_pmc, pubmed_pmc_refs") rejected(function() pubmed.getLinks(1, "pubmed_gene") end, "linkname must be one of") rejected(function() pubmed.getLinks(1, "pubmed_pubmed", {scores = "yes"}) end, "scores must be true or false") rejected(function() pubmed.getLinks(1, "pubmed_pubmed", {cmd = "prlinks"}) end, "getLinks received an unknown option cmd") rejected(function() pubmed.getLinks(1, "pubmed_pubmed", "scores") end, "getLinks options must be a table") for _, id in {"PMC", "PMC0", "PMC12a", "PMC1/../x", "PMC12345678901", "NIHMS123", "", "0", 0, 1.5, "1234567890", {"PMC1"}} do rejected(function() pubmed.getFullText(id) end, "id must be a PMCID such as PMC4412151 or a PMID such as 25977807") end local function upstream(code, body, headers, call, expected, absent) status, payload, responseHeaders = code, body, headers local before = calls local ok, err = pcall(call) for _, text in expected do assert(not ok and string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err)) end if absent then assert(not string.find(tostring(err), absent, 1, true), "unexpected " .. absent .. " in " .. tostring(err)) end assert(calls == before + 1, "a failed request was repeated") end local find = search({term = "crispr"}) local function summaries() pubmed.getSummaries(1) end local function records() pubmed.getRecords(1) end local function links() pubmed.getLinks(1, "pubmed_pubmed") end local function fullText() pubmed.getFullText("PMC1") end local JSON = {["content-type"] = {"application/json"}} upstream(429, '{"error":"API rate limit exceeded","api-key":"203.0.113.9","count":"4","limit":"3"}', {["retry-after"] = {"2"}}, find, {"NCBI HTTP 429: API rate limit exceeded; retry after 2s", '"retryable":true', '"upstream_status":429'}) upstream(429, "<html><title>Too Many Requests</title></html>", {["retry-after"] = {"Thu, 29 Oct 2026 20:00:00 GMT"}}, fullText, {"NCBI HTTP 429; retry after Thu, 29 Oct 2026 20:00:00 GMT", '"retryable":true'}, "GMTs") upstream(400, '{"error":"API key invalid","api-key":"[redacted]","type":"invalid","status":"unknown"}', {}, summaries, {"NCBI HTTP 400: API key invalid", '"retryable":false'}) upstream(400, '<?xml version="1.0"?>\n<eFetchResult>\n\t<ERROR>Database: nope - is not supported</ERROR>\n</eFetchResult>', {}, records, {"NCBI HTTP 400: Database: nope - is not supported", '"retryable":false'}) upstream(414, "<html><body>Request-URI Too Long</body></html>", {}, links, {"NCBI HTTP 414", '"retryable":false'}, "Request-URI") upstream(400, '{"error":"' .. string.rep("y", 1000) .. '"}', {}, find, {"NCBI HTTP 400: " .. string.rep("y", 300)}, string.rep("y", 301)) upstream(500, "", {}, find, {"NCBI HTTP 500", '"retryable":true'}) upstream(502, "<html>Bad Gateway</html>", {}, fullText, {"NCBI HTTP 502", '"retryable":true'}, "Gateway") upstream(503, "", {["retry-after"] = {"30"}}, records, {"NCBI HTTP 503; retry after 30s", '"retryable":true'}) upstream(301, "", {location = {"https://www.ncbi.nlm.nih.gov/elsewhere"}}, find, {"NCBI HTTP 301: unexpected redirect", '"retryable":false'}, "elsewhere") -- Errors inside a successful answer: known input rejections are final, other failures are server faults. upstream(200, '{"esearchresult":{"ERROR":"Search Backend failed: An error occurred while processing request.\\nStatus: 500."}}', {}, find, {"NCBI: Search Backend failed: An error occurred while processing request. Status: 500.", '"retryable":true', '"upstream_status":200'}) upstream(200, '{"esummaryresult":["Unable to obtain query #1"]}', {}, summaries, {"NCBI: Unable to obtain query #1", '"retryable":true'}) upstream(200, '{"error":"Too many UIDs in request. Maximum number of UIDs is 500 for JSON format output."}', {}, summaries, {"NCBI: Too many UIDs in request.", '"retryable":false'}) upstream(200, '{"ERROR":"Invalid linkname"}', {}, links, {"NCBI: Invalid linkname", '"retryable":false'}) -- NCBI answers a query of only parentheses this way: it names the empty term after its generic outage text. upstream(200, '{"esearchresult":{"ERROR":"Search Backend failed: An error occurred while processing request. Status: 500. Details: Search is temporarily unavailable. Please try again later. Details: Empty Term in the request"}}', {}, find, {"Empty Term in the request", '"retryable":false'}) upstream(200, '{"error":"API key not wellformed"}', {}, summaries, {"NCBI: API key not wellformed", '"retryable":false'}) upstream(200, "<html>maintenance</html>", {}, find, {"NCBI returned an invalid JSON object", '"retryable":false'}, "maintenance") upstream(200, "[]", {}, summaries, {"NCBI returned an invalid JSON object"}) -- ELink stops after about 15 s and then sends an empty 200. upstream(200, "", {}, links, {"NCBI returned an empty answer; retry, or pass fewer ids", '"retryable":true'}) upstream(200, '{"result":"none"}', {}, summaries, {"NCBI returned an unexpected answer", '"retryable":false'}) upstream(200, '{"header":{}}', {}, links, {"NCBI returned an unexpected answer"}) upstream(200, "<eFetchResult><ERROR>Backend unavailable</ERROR></eFetchResult>", {}, records, {"NCBI: Backend unavailable", '"retryable":true'}) upstream(200, "<html><body>Maintenance</body></html>", {}, records, {"NCBI returned an unexpected MEDLINE answer", '"retryable":false'}, "Maintenance") upstream(200, "TI - No PMID\n", {}, records, {"NCBI returned a MEDLINE record without a PMID", '"retryable":false'}) upstream(200, "[Error] : No result can be found. <BR><HR><B> - https://www.ncbi.nlm.nih.gov/research/bionlp/RESTful/</B>", {["content-type"] = {"text/html"}}, fullText, {"PMC has no open-access full text for PMC1; only open-access and author manuscript articles have one", '"retryable":false'}, "<BR>") upstream(200, "<html>Service unavailable</html>", {["content-type"] = {"text/html"}}, fullText, {"NCBI returned an unexpected full-text answer"}, "Service") upstream(200, "[]", JSON, fullText, {"NCBI returned an unexpected full-text answer"}) upstream(200, '[{"documents":[{"id":"PMC1"}]}]', JSON, fullText, {"unexpected full-text answer"}) upstream(200, '{"documents":[]}', JSON, fullText, {"unexpected full-text answer"}) upstream(200, '{"x":"' .. string.rep("z", 4 * 1024 * 1024) .. '"}', JSON, fullText, {"NCBI returned more data than one call can hold; this article's full text is too large for one call", '"retryable":false'}, "limit") upstream(200, string.rep("PMID- 1\n\n", 600 * 1024), {}, records, {"more data than one call can hold; request fewer IDs"}) upstream(200, '{"esearchresult":{"x":"' .. string.rep("z", 4 * 1024 * 1024) .. '"}}', {}, find, {"more data than one call can hold; lower retmax"}) requestError = {code = "timeout", message = "request deadline"} upstream(200, "", {}, find, {"NCBI did not answer within 8 s; retry", '"retryable":true'}) -- Other request failures pass through unchanged, message included, and never become an upstream failure. requestError = {code = "access_denied", message = "origin not allowed"} upstream(200, "", {}, fullText, {"origin not allowed"}, "retryable") requestError = nil readError = {code = "timeout", message = "await timed out"} upstream(200, "", {}, summaries, {"NCBI did not finish sending its answer within 19 s; retry", '"retryable":true'}) readError = {code = "io_error", message = "connection reset by peer"} upstream(200, "", {}, links, {"NCBI response failed: connection reset by peer", '"retryable":true'}, "more data") -- An error body that stalls or breaks still gives the structured failure. upstream(503, "", {}, find, {"NCBI HTTP 503", '"retryable":true', '"upstream_status":503'}, "reset") readError = {code = "timeout", message = "await timed out"} upstream(400, "", {}, records, {"NCBI HTTP 400", '"retryable":false', '"upstream_status":400'}, "timed out") readError = {code = "cancelled", message = "invocation cancelled"} local before = calls local ok, err = pcall(records) -- A stand-in error loses its native identity across the export boundary; it must still not become an upstream failure. assert(not ok and not string.find(tostring(err), "retryable", 1, true), "cancellation became an upstream error: " .. tostring(err)) assert(calls == before + 1) readError = nil end, }manifest.luau
return { contract = function(m) local pubmedEUtilities = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils" local pubmedBioC = "https://www.ncbi.nlm.nih.gov/research/bionlp/RESTful/pmcoa.cgi/BioC_json" local resolvePubMed = function(key) local config = {} if key ~= "" then config.api_key = key end local r, err = m.resolve(nil, config, nil, "") assert(not err, tostring(err)) return r end -- TestPubMedPublicReadRoutes do for _, key in { "", "synthetic-ncbi-key" } do local r = resolvePubMed(key) m.routes(r, "", true, { "POST " .. pubmedEUtilities .. "/esearch.fcgi", "POST " .. pubmedEUtilities .. "/esummary.fcgi", "POST " .. pubmedEUtilities .. "/efetch.fcgi", "POST " .. pubmedEUtilities .. "/elink.fcgi", "GET " .. pubmedBioC .. "/PMC4412151/unicode", "GET " .. pubmedBioC .. "/25977807/unicode", }) m.routes(r, "", false, { "GET " .. pubmedEUtilities .. "/esearch.fcgi?db=pubmed&term=x", "POST " .. pubmedEUtilities .. "/epost.fcgi", "POST " .. pubmedEUtilities .. "/einfo.fcgi", "POST " .. pubmedEUtilities .. "/espell.fcgi", "GET " .. pubmedEUtilities .. "/ecitmatch.cgi", "POST " .. pubmedEUtilities .. "/esearch.fcgi/x", "POST https://eutils.ncbi.nlm.nih.gov.example.com/entrez/eutils/esearch.fcgi", "POST http://eutils.ncbi.nlm.nih.gov:8080/entrez/eutils/esearch.fcgi", "POST https://www.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi", "POST " .. pubmedBioC .. "/PMC4412151/unicode", "GET " .. pubmedBioC .. "/PMC4412151/ascii", "GET " .. pubmedBioC .. "/%2e%2e/unicode", "GET https://www.ncbi.nlm.nih.gov/research/bionlp/RESTful/pubmed.cgi/BioC_json/25977807/unicode", "GET https://www.ncbi.nlm.nih.gov/research/pubtator3-api/publications/export/biocjson", "GET https://pmc.ncbi.nlm.nih.gov/tools/idconv/api/v1/articles/", "GET https://ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi", }) end end -- TestPubMedSendsTheKeyOnlyToEUtilities do local dropped = { "Authorization", "Cookie" } for _, key in { "", "synthetic-ncbi-key" } do local r = resolvePubMed(key) local search = pubmedEUtilities .. "/esearch.fcgi" if key ~= "" then search ..= "?api_key=" .. key end for _, route in { { method = "POST", url = pubmedEUtilities .. "/esearch.fcgi", want = search }, { method = "GET", url = pubmedBioC .. "/PMC4412151/unicode", want = pubmedBioC .. "/PMC4412151/unicode", }, } do local recipe, err = m.recipe(r, route.method, route.url, nil) assert(not err, tostring(err)) do local prepared, err = m.prepareUrl(recipe, r.Context) if (err ~= nil) or (prepared ~= route.want) then m.fail("key %s: %s prepared as %s: %s", key, route.url, prepared, err) end end m.rejectPreparedOverrides(recipe, r.Context, route.method .. " " .. route.url) local caller = { ["Content-Type"] = { "application/x-www-form-urlencoded" } } for _, name in dropped do caller[name] = { "caller-value" } end local headers, err = m.prepare(recipe, r.Context, caller) if (err ~= nil) or (m.header(headers, "Content-Type") ~= "application/x-www-form-urlencoded") then m.fail("prepare: %s %s", headers, err) end for _, name in dropped do if m.header(headers, name) ~= "" then m.fail("%s reached NCBI", name) end end end end end -- TestPubMedEmptyKeyNeverReachesNCBI do local r, err = m.resolve(nil, { api_key = "" }, nil, "") if err == nil then local recipe, err = m.recipe(r, "POST", pubmedEUtilities .. "/esearch.fcgi", nil) assert(not err, tostring(err)) local prepared, _ = m.prepareUrl(recipe, r.Context) m.fail("an empty key resolved and prepared %s", prepared) end end end, }reads.luau
-- Each export posts one exact E-utilities form, or reads one BioC document, and returns NCBI's data. return { scenario = {publisher = {}, config = {}, auth_method = "", auth_config = {}}, configure = function() requests, responses = {}, {} http = {request = function(req) table.insert(requests, req) assert(req.headers == nil or req.headers.Authorization == nil, "the public API takes no credentials") assert(req.timeoutMs == 8000, "headers get the call's time less the body's share") assert(#responses > 0, "unexpected request: " .. req.url) local queued = table.remove(responses, 1) return fixture.operation({statusCode = 200, headers = {["content-type"] = {queued.type}}, body = fixture.reader(queued.body)}) end} function respond(body, kind) table.insert(responses, {body = body, type = kind or "application/json; charset=UTF-8"}) end end, run = function(pubmed) local EUTILS = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/" local CONTACT = "&tool=houston&email=hello%40ok-houston.com" local function last() return requests[#requests] end local function posted(utility, body) local req = last() assert(req.method == "POST" and req.url == EUTILS .. utility .. ".fcgi", req.url) assert(req.headers["Content-Type"][1] == "application/x-www-form-urlencoded") assert(req.body == body .. CONTACT, req.body) end local names = {} for name, fn in pubmed do assert(type(fn) == "function") table.insert(names, name) end table.sort(names) assert(table.concat(names, ",") == "getFullText,getLinks,getRecords,getSummaries,searchArticles", table.concat(names, ",")) assert(#requests == 0, "initialization reached NCBI") -- A minimal search keeps NCBI's defaults and its string counts; an empty idlist stays an array. respond('{"header":{"type":"esearch","version":"0.3"},"esearchresult":{"count":"0","retmax":"0","retstart":"0","idlist":[],' .. '"translationset":[],"querytranslation":"zzqx[All Fields]","warninglist":{"outputmessages":["No items found."]}}}') local found = pubmed.searchArticles({term = "zzqx"}) posted("esearch", "db=pubmed&retmode=json&term=zzqx&retstart=0&retmax=20") assert(found.count == "0" and json.encode(found.idlist) == "[]" and found.warninglist.outputmessages[1] == "No items found.") assert(found.header == nil, "the result is esearchresult") -- Every option, encoded in a fixed order; the caller's table is left unchanged. local opts = {term = 'crispr[tiab] AND "Smith J"[au]', retstart = 9990, retmax = 9999, sort = "pub_date", mindate = "2024/01", maxdate = "2024/12/31", datetype = "pdat"} respond('{"esearchresult":{"count":"8026","retmax":"9","retstart":"9990","idlist":["42205224","41255389"]}}') found = pubmed.searchArticles(opts) posted("esearch", "db=pubmed&retmode=json&term=crispr%5Btiab%5D%20AND%20%22Smith%20J%22%5Bau%5D&retstart=9990&retmax=9999" .. "&sort=pub_date&mindate=2024%2F01&maxdate=2024%2F12%2F31&datetype=pdat") assert(found.count == "8026" and #found.idlist == 2 and found.idlist[2] == "41255389") assert(opts.retmax == 9999 and opts.term == 'crispr[tiab] AND "Smith J"[au]', "caller options were modified") respond('{"esearchresult":{"count":"918","retmax":"0","retstart":"0","idlist":[]}}') pubmed.searchArticles({term = "crispr", retmax = 0, reldate = 30, datetype = "edat", sort = "relevance"}) posted("esearch", "db=pubmed&retmode=json&term=crispr&retstart=0&retmax=0&sort=relevance&reldate=30&datetype=edat") -- Leap days, partial dates and one-day ranges are valid. respond('{"esearchresult":{"count":"1","retmax":"0","retstart":"0","idlist":[]}}') pubmed.searchArticles({term = "crispr", mindate = "2024/02/29", maxdate = "2024/02/29"}) respond('{"esearchresult":{"count":"1","retmax":"0","retstart":"0","idlist":[]}}') pubmed.searchArticles({term = "crispr", mindate = "2000/02/29", maxdate = "2000/02"}) posted("esearch", "db=pubmed&retmode=json&term=crispr&retstart=0&retmax=20&mindate=2000%2F02%2F29&maxdate=2000%2F02") -- Summaries take numbers, strings and lists, drop repeats and keep NCBI's per-ID errors. respond('{"header":{"type":"esummary"},"result":{"uids":["31452104","99999999"],"31452104":{"uid":"31452104",' .. '"title":"Molegro Virtual Docker for Docking.","authors":[{"name":"Bitencourt-Ferreira G","authtype":"Author"}],' .. '"articleids":[{"idtype":"doi","value":"10.1007/978-1-4939-9752-7_10"}]},' .. '"99999999":{"uid":"99999999","error":"cannot get document summary"}}}') local summaries = pubmed.getSummaries({31452104, "99999999", "31452104"}) posted("esummary", "db=pubmed&retmode=json&id=31452104%2C99999999") assert(summaries.uids[1] == "31452104" and summaries["31452104"].authors[1].name == "Bitencourt-Ferreira G") assert(summaries["99999999"].error == "cannot get document summary") respond('{"result":{"uids":["1"],"1":{"uid":"1"}}}') pubmed.getSummaries("1, 2 3,,4") posted("esummary", "db=pubmed&retmode=json&id=1%2C2%2C3%2C4") respond('{"result":{"uids":["5"],"5":{"uid":"5"}}}') pubmed.getSummaries(5) posted("esummary", "db=pubmed&retmode=json&id=5") -- MEDLINE records: continuation lines join, authors keep their IDs and affiliations, other tags stay in order. respond(table.concat({ "", "PMID- 33782057", "OWN - NLM", "DP - 2021 Mar 29", "TI - The PRISMA 2020 statement: an updated guideline for reporting systematic ", " reviews.", "LID - 10.1136/bmj.n71 [doi]", "LID - n71", "AB - BACKGROUND: Systematic reviews are useful. METHODS: We updated the", -- Only an empty line ends a record; a line of spaces inside a value is ignored. " ", " guideline. CONCLUSIONS: Use it.", "FAU - Page, Matthew J", "AU - Page MJ", "AUID- ORCID: 0000-0002-4242-7526", "AD - School of Public Health and Preventive Medicine, Monash University, Melbourne, ", " Australia [email protected].", "FAU - McKenzie, Joanne E", "AU - McKenzie JE", "AD - Monash University.", "AD - University of Ottawa.", "CN - PRISMA Group", "AD - PRISMA secretariat.", "LA - eng", "PT - Journal Article", "PT - Review", "MH - Checklist", "MH - *Guidelines as Topic", "MH - Proteins/*chemistry", "OTO - NOTNLM", "OT - reporting", "PMC - PMC8005924", "SO - BMJ. 2021 Mar 29;372:n71. doi: 10.1136/bmj.n71.", "", "PMID- 1", "TI - Formate assay in body fluids: application in methanol poisoning.", "AU - Makar AB", "AU - McMartin KE", "", "PMID- 2", "TI - A record without authors.", "", }, "\n"), "text/plain; charset=UTF-8") local records = pubmed.getRecords({"33782057", 1, "2"}).records posted("efetch", "db=pubmed&rettype=medline&retmode=text&id=33782057%2C1%2C2") assert(#records == 3) local prisma = records[1] assert(prisma.PMID == "33782057" and prisma.OWN == "NLM" and prisma.DP == "2021 Mar 29") assert(prisma.TI == "The PRISMA 2020 statement: an updated guideline for reporting systematic reviews.", prisma.TI) assert(prisma.AB == "BACKGROUND: Systematic reviews are useful. METHODS: We updated the guideline. CONCLUSIONS: Use it.", "wrapped lines join with one space, as Biopython joins them: " .. prisma.AB) assert(table.concat(prisma.LID, "|") == "10.1136/bmj.n71 [doi]|n71") assert(#prisma.authors == 3 and prisma.authors[1].FAU == "Page, Matthew J" and prisma.authors[1].AU == "Page MJ") assert(prisma.authors[1].AUID[1] == "ORCID: 0000-0002-4242-7526") assert(prisma.authors[1].AD[1] == "School of Public Health and Preventive Medicine, Monash University, Melbourne, Australia [email protected].") assert(table.concat(prisma.authors[2].AD, "|") == "Monash University.|University of Ottawa." and prisma.authors[2].AUID == nil) assert(prisma.FAU == nil and prisma.AU == nil and prisma.AD == nil, "author tags live in authors") -- A corporate author is its own entry, so its affiliation does not go to the person before it. assert(prisma.authors[3].CN == "PRISMA Group" and prisma.authors[3].AD[1] == "PRISMA secretariat." and prisma.authors[3].AU == nil) assert(prisma.CN == nil and prisma.LA[1] == "eng" and table.concat(prisma.PT, "|") == "Journal Article|Review") assert(table.concat(prisma.MH, "|") == "Checklist|*Guidelines as Topic|Proteins/*chemistry") assert(prisma.OTO[1] == "NOTNLM" and prisma.OT[1] == "reporting" and prisma.PMC == "PMC8005924") assert(prisma.SO == "BMJ. 2021 Mar 29;372:n71. doi: 10.1136/bmj.n71.") -- Older records list authors by AU alone. assert(#records[2].authors == 2 and records[2].authors[2].AU == "McMartin KE" and records[2].authors[2].FAU == nil) assert(json.encode(records[3].authors) == "[]", "a record without authors keeps an empty array") respond("\n", "text/plain; charset=UTF-8") records = pubmed.getRecords("99999999").records assert(json.encode(records) == "[]", "unknown PMIDs are left out") -- Lines that are not tagged, such as NCBI's note about a PMID it cannot serve, are skipped rather than failing the -- batch; a tag line may have an empty value without a trailing space. respond(table.concat({"id: 99999999 Error occurred: The following PMID is not available", " stray continuation", "", "PMID- 31452104", "AB -", "not tagged", "TI - Molegro Virtual Docker", " for Docking.", ""}, "\n"), "text/plain; charset=UTF-8") records = pubmed.getRecords({99999999, 31452104}).records assert(#records == 1 and records[1].PMID == "31452104" and records[1].AB == "", json.encode(records)) assert(records[1].TI == "Molegro Virtual Docker for Docking.", records[1].TI) -- Links: one id parameter per PMID, so each gets its own linkset; absent linksetdbs pass through. respond('{"header":{"type":"elink"},"linksets":[{"dbfrom":"pubmed","ids":["25977807"],"linksetdbs":[{"dbto":"pubmed",' .. '"linkname":"pubmed_pubmed_citedin","links":["32535840","31722288"]}]},{"dbfrom":"pubmed","ids":["99999999"]}]}') local linksets = pubmed.getLinks({25977807, "99999999"}, "pubmed_pubmed_citedin") posted("elink", "dbfrom=pubmed&retmode=json&id=25977807&id=99999999&linkname=pubmed_pubmed_citedin&cmd=neighbor") assert(#linksets == 2 and linksets[1].linksetdbs[1].links[2] == "31722288" and linksets[2].linksetdbs == nil) respond('{"linksets":[{"dbfrom":"pubmed","ids":["25977807"],"linksetdbs":[{"dbto":"pubmed","linkname":"pubmed_pubmed",' .. '"links":[{"id":"25194848","score":26054440}]}]}]}') linksets = pubmed.getLinks("25977807", "pubmed_pubmed", {scores = true}) posted("elink", "dbfrom=pubmed&retmode=json&id=25977807&linkname=pubmed_pubmed&cmd=neighbor_score") assert(linksets[1].linksetdbs[1].links[1].score == 26054440) for _, name in {"pubmed_pubmed_reviews", "pubmed_pubmed_refs", "pubmed_pmc", "pubmed_pmc_refs"} do respond('{"linksets":[]}') assert(json.encode(pubmed.getLinks(1, name, {scores = false})) == "[]") posted("elink", "dbfrom=pubmed&retmode=json&id=1&linkname=" .. name .. "&cmd=neighbor") end -- Full text: one bodiless GET by PMCID or PMID, returning the BioC document unchanged. local document = '{"bioctype":"BioCDocument","id":"PMC4412151","infons":{"license":"CC BY"},"passages":[' .. '{"offset":0,"infons":{"section_type":"TITLE","type":"front","article-id_pmid":"25977807"},"text":"Title"},' .. '{"offset":6,"infons":{"section_type":"INTRO","type":"paragraph"},"text":"Neuroscience is transforming."}],' .. '"annotations":[],"relations":[]}' local BIOC = "https://www.ncbi.nlm.nih.gov/research/bionlp/RESTful/pmcoa.cgi/BioC_json/" for _, case in {{id = "pmc4412151", path = "PMC4412151"}, {id = 25977807, path = "25977807"}, {id = "25977807", path = "25977807"}} do respond('[{"bioctype":"BioCCollection","source":"PMC","documents":[' .. document .. "]}]", "application/json") local article = pubmed.getFullText(case.id) assert(last().method == "GET" and last().body == nil and last().url == BIOC .. case.path .. "/unicode", last().url) assert(article.id == "PMC4412151" and article.infons.license == "CC BY" and #article.passages == 2) assert(article.passages[2].infons.section_type == "INTRO" and json.encode(article.annotations) == "[]") end end, }