Official

ChEMBL

Let agents search molecules, similar structures, drug targets and bioactivity measurements, and read the assays, publications, mechanisms and indications behind them. Access is read-only and requires no account.

ChEMBL data uses CC BY-SA 3.0. Credit ChEMBL and EMBL-EBI, and share adapted data under the same licence.

EMBL-EBI's terms apply. This connector is not affiliated with EMBL-EBI.

Add ChEMBL.

Setup instructions

Add ChEMBL

Select Add connection in Houston. No account, API key or settings are required.

For a missing molecule, search by name to find its ChEMBL ID. Structure searches need valid SMILES; substructures need at least five characters.

ChEMBL web services.

Files

  • connector.luau
    -- ChEMBL data web services (https://www.ebi.ac.uk/chembl/api/data), public and read-only. Arguments and results keep ChEMBL's native field names.
    type Options = {[string]: any}
    -- Each resource lists its fields as space-separated names; the loop after RESOURCES derives the rest.
    type Resource = {name: string, path: string, rows: string, label: string, search: boolean, id: string, about: string,
    	compact: string, fields: string, sort: string, filters: {[string]: string}, only: string, compactSet: {[string]: boolean},
    	fieldSet: {[string]: boolean}, sortSet: {[string]: boolean}, filterKinds: {[string]: string}}
    
    local API = "https://www.ebi.ac.uk/chembl/api/data"
    -- ChEMBL serves at most 1,000 rows per page. Houston ends a call after 30 s and an uncached ChEMBL page can take 5 to
    -- 15 s, so a call reads at most two pages within a 27 s budget. The sandbox has no clock, so each wait gets a fixed
    -- share: the second page keeps 9 s, and each response body, an error body included, 3 s of its page's share.
    local DEFAULT_LIMIT, MAX_LIMIT, PAGE_SIZE, MAX_PAGES = 100, 2000, 1000, 2
    local CALL_TIME, LATER_TIME, BODY_TIME = 27000, 9000, 3000
    local MAX_BYTES = 4 * 1024 * 1024
    -- Upper bounds of one row in bytes, which size the first page from the byte budget.
    local COMPACT_ROW, FULL_ROW = 2048, 128 * 1024
    -- ChEMBL's server refuses request lines over 4,094 bytes; later pages add up to 40 bytes of paging.
    local MAX_URL, PAGING_BYTES = 4000, 40
    local MAX_TEXT, MAX_OFFSET, MAX_SORT = 1000, 2 ^ 31 - 1, 3
    local MIN_SIMILARITY, DEFAULT_SIMILARITY, MIN_SUBSTRUCTURE = 40, 80, 5
    local CHEMBL_ID = "^CHEMBL%d+$"
    local INCHIKEY = "^" .. string.rep("%u", 14) .. "%-" .. string.rep("%u", 10) .. "%-%u$"
    
    local function words(list: string): {string}
    	local out: {string} = {}
    	for word in string.gmatch(list, "%S+") do table.insert(out, word) end
    	return out
    end
    
    local function set(list: string): {[string]: boolean}
    	local out: {[string]: boolean} = {}
    	for _, word in words(list) do out[word] = true end
    	return out
    end
    
    -- Filter kinds, in help order, and the lookups ChEMBL accepts for each.
    local KINDS = table.freeze({"text", "term", "number", "flag", "id", "smiles"})
    local LOOKUP_LISTS: {[string]: string} = table.freeze({
    	text = "exact iexact contains icontains startswith istartswith endswith iendswith regex iregex in isnull",
    	term = "exact iexact in isnull",
    	number = "exact gt gte lt lte range in isnull",
    	flag = "exact isnull",
    	id = "exact in",
    	smiles = "flexmatch connectivity",
    })
    local LOOKUPS: {[string]: {[string]: boolean}} = {}
    local ANY_LOOKUP: {[string]: boolean} = {}
    for kind, list in LOOKUP_LISTS do
    	LOOKUPS[kind] = set(list)
    	for lookup in LOOKUPS[kind] do ANY_LOOKUP[lookup] = true end
    end
    
    local PROPERTIES = "molecule_properties__alogp molecule_properties__aromatic_rings molecule_properties__full_mwt "
    	.. "molecule_properties__hba molecule_properties__hbd molecule_properties__heavy_atoms molecule_properties__mw_freebase "
    	.. "molecule_properties__np_likeness_score molecule_properties__num_ro5_violations molecule_properties__psa "
    	.. "molecule_properties__qed_weighted molecule_properties__rtb"
    -- Molecule fields and filters shared by the structure searches, which ignore synonyms.
    local STRUCTURE_FIELDS = "atc_classifications availability_type biotherapeutic black_box_warning chemical_probe chirality "
    	.. "cross_references dosed_ingredient first_approval first_in_class helm_notation inorganic_flag max_phase "
    	.. "molecule_chembl_id molecule_hierarchy molecule_properties molecule_structures molecule_type natural_product oral "
    	.. "orphan parenteral polymer_flag pref_name prodrug structure_type therapeutic_flag topical usan_stem "
    	.. "usan_stem_definition usan_substem usan_year veterinary withdrawn_flag"
    local STRUCTURE_TEXT = "pref_name molecule_type structure_type availability_type helm_notation usan_stem "
    	.. "usan_stem_definition usan_substem atc_classifications__level5 molecule_structures__standard_inchi_key "
    	.. "molecule_properties__full_molformula molecule_properties__ro3_pass"
    local STRUCTURE_FILTERS = table.freeze({
    	text = STRUCTURE_TEXT,
    	number = "max_phase first_approval usan_year chirality veterinary " .. PROPERTIES,
    	flag = "oral parenteral topical black_box_warning natural_product first_in_class prodrug inorganic_flag "
    		.. "polymer_flag therapeutic_flag dosed_ingredient withdrawn_flag chemical_probe orphan",
    	id = "molecule_chembl_id molecule_hierarchy__parent_chembl_id",
    	smiles = "molecule_structures__canonical_smiles",
    })
    local STRUCTURE_SORT = "molecule_chembl_id pref_name max_phase first_approval usan_year molecule_type structure_type " .. PROPERTIES
    local MOLECULE_COMPACT = "molecule_chembl_id pref_name max_phase molecule_type first_approval molecule_properties"
    
    local RESOURCES: {Resource} = ({
    	{name = "Molecule", path = "molecule", rows = "molecules", label = "molecule", search = true, id = "molecule",
    		about = "Compounds, biologics and approved drugs. id is a ChEMBL ID such as CHEMBL25 or a standard InChIKey. q searches names and synonyms. Find an exact structure with filters `[\"molecule_structures__canonical_smiles__flexmatch\"] = smiles` (or `__connectivity` to ignore stereochemistry and salts), a trade name with `molecule_synonyms__molecule_synonym__iexact`. max_phase is the highest development phase, returned as a string such as \"4.0\" (approved); filter it as a number.",
    		compact = MOLECULE_COMPACT, fields = STRUCTURE_FIELDS .. " molecule_synonyms", sort = STRUCTURE_SORT,
    		filters = {text = STRUCTURE_TEXT .. " molecule_synonyms__molecule_synonym", number = STRUCTURE_FILTERS.number,
    			flag = STRUCTURE_FILTERS.flag, id = STRUCTURE_FILTERS.id, smiles = STRUCTURE_FILTERS.smiles}},
    	{name = "Target", path = "target", rows = "targets", label = "target", search = true, id = "chembl",
    		about = "Proteins, complexes, cell lines and organisms that compounds act on. id is a ChEMBL ID such as CHEMBL203. Find a protein by UniProt accession with `target_components__accession`.",
    		compact = "target_chembl_id pref_name target_type organism tax_id",
    		fields = "cross_references organism pref_name species_group_flag target_chembl_id target_components target_type tax_id",
    		sort = "organism tax_id pref_name target_type species_group_flag target_chembl_id",
    		filters = {text = "pref_name organism target_type target_components__accession", number = "tax_id",
    			flag = "species_group_flag", id = "target_chembl_id"}},
    	{name = "Activity", path = "activity", rows = "activities", label = "activity", search = true, id = "integer",
    		about = "Measured bioactivities (IC50, Ki, EC50, inhibition...) of a molecule in an assay. id is the integer activity_id. Prefer standard_* fields; pchembl_value is -log10 of the molar potency, for comparable IC50/Ki/EC50/Kd values. Filter by molecule_chembl_id, target_chembl_id, assay_chembl_id or document_chembl_id rather than listing all 24 million.",
    		compact = "activity_id molecule_chembl_id molecule_pref_name target_chembl_id target_pref_name target_organism "
    			.. "assay_chembl_id assay_type document_chembl_id standard_type standard_relation standard_value standard_units pchembl_value",
    		fields = "action_type activity_comment activity_id activity_properties assay_chembl_id assay_description assay_type "
    			.. "assay_variant_accession assay_variant_mutation bao_endpoint bao_format bao_label canonical_smiles "
    			.. "data_validity_comment data_validity_description document_chembl_id document_journal document_year "
    			.. "ligand_efficiency modality molecule_chembl_id molecule_pref_name parent_molecule_chembl_id pchembl_value "
    			.. "potential_duplicate qudt_units record_id relation src_id standard_flag standard_relation standard_text_value "
    			.. "standard_type standard_units standard_upper_value standard_value target_chembl_id target_organism "
    			.. "target_pref_name target_tax_id text_value toid type units uo_units upper_value value",
    		sort = "activity_id pchembl_value standard_value standard_type standard_units document_year molecule_chembl_id "
    			.. "molecule_pref_name target_chembl_id target_pref_name target_organism assay_chembl_id assay_type document_chembl_id",
    		filters = {term = "standard_type standard_relation standard_units assay_type target_organism target_pref_name "
    				.. "molecule_pref_name activity_comment assay_description document_journal modality standard_text_value "
    				.. "relation type units qudt_units uo_units text_value assay_variant_accession assay_variant_mutation",
    			number = "pchembl_value standard_value standard_upper_value activity_id document_year target_tax_id record_id value upper_value",
    			flag = "potential_duplicate standard_flag",
    			id = "molecule_chembl_id parent_molecule_chembl_id target_chembl_id assay_chembl_id document_chembl_id"}},
    	{name = "Assay", path = "assay", rows = "assays", label = "assay", search = true, id = "chembl",
    		about = "Experiments that produced activities. id is a ChEMBL ID such as CHEMBL1217643. assay_type is B (binding), F (functional), A (ADME), T (toxicity), P (physicochemical) or U (unassigned); confidence_score 0 to 9 rates the target assignment (9: single protein, direct).",
    		compact = "assay_chembl_id description assay_type assay_organism target_chembl_id document_chembl_id confidence_score",
    		fields = "aidx assay_category assay_cell_type assay_chembl_id assay_classifications assay_group assay_organism "
    			.. "assay_parameters assay_strain assay_subcellular_fraction assay_tax_id assay_test_type assay_tissue assay_type "
    			.. "assay_type_description bao_format bao_label cell_chembl_id confidence_description confidence_score "
    			.. "description document_chembl_id relationship_description relationship_type src_assay_id src_id "
    			.. "target_chembl_id tissue_chembl_id variant_sequence",
    		sort = "assay_chembl_id assay_type assay_organism assay_tax_id confidence_score target_chembl_id document_chembl_id src_id",
    		filters = {text = "description assay_type assay_organism assay_category assay_cell_type assay_tissue assay_strain "
    				.. "assay_subcellular_fraction assay_test_type relationship_type cell_chembl_id aidx assay_group",
    			number = "confidence_score assay_tax_id src_id src_assay_id",
    			id = "assay_chembl_id target_chembl_id document_chembl_id"}},
    	{name = "Document", path = "document", rows = "documents", label = "document", search = true, id = "chembl",
    		about = "Publications, patents and datasets ChEMBL extracted data from. id is a ChEMBL ID such as CHEMBL1139451. Look up a paper with `pubmed_id` or `doi`.",
    		compact = "document_chembl_id title journal year doi pubmed_id doc_type",
    		fields = "abstract authors chembl_release contact doc_type document_chembl_id doi doi_chembl first_page issue "
    			.. "journal journal_full_title last_page patent_id pubmed_id src_id title volume year",
    		sort = "document_chembl_id year pubmed_id doi title journal doc_type",
    		filters = {text = "title abstract authors journal journal_full_title doc_type doi doi_chembl patent_id volume "
    				.. "issue first_page last_page contact",
    			number = "year pubmed_id", id = "document_chembl_id"}},
    	{name = "Mechanism", path = "mechanism", rows = "mechanisms", label = "mechanism", search = false, id = "integer",
    		about = "Curated mechanisms of action of drugs and clinical candidates. id is the integer mec_id. Filter by the parent molecule: parent_molecule_chembl_id, or molecule_chembl_id with the parent's ID.",
    		compact = "mec_id molecule_chembl_id parent_molecule_chembl_id target_chembl_id mechanism_of_action action_type max_phase",
    		fields = "action_type binding_site_comment direct_interaction disease_efficacy max_phase mec_id mechanism_comment "
    			.. "mechanism_of_action mechanism_refs molecular_mechanism molecule_chembl_id parent_molecule_chembl_id "
    			.. "record_id selectivity_comment site_id target_chembl_id variant_sequence",
    		sort = "mec_id molecule_chembl_id parent_molecule_chembl_id target_chembl_id action_type mechanism_of_action max_phase",
    		filters = {text = "action_type mechanism_of_action mechanism_comment selectivity_comment binding_site_comment",
    			number = "max_phase mec_id record_id site_id", flag = "direct_interaction disease_efficacy molecular_mechanism",
    			id = "molecule_chembl_id parent_molecule_chembl_id target_chembl_id"}},
    	{name = "DrugIndication", path = "drug_indication", rows = "drug_indications", label = "drug indication", search = false,
    		id = "integer",
    		about = "Diseases that drugs and clinical candidates are approved or studied for, with EFO and MeSH terms. id is the integer drugind_id. Filter by parent_molecule_chembl_id, or molecule_chembl_id with the parent's ID; max_phase_for_ind is the highest phase for that indication.",
    		compact = "drugind_id molecule_chembl_id parent_molecule_chembl_id efo_id efo_term mesh_id mesh_heading max_phase_for_ind",
    		fields = "drugind_id efo_id efo_term indication_refs max_phase_for_ind mesh_heading mesh_id molecule_chembl_id "
    			.. "parent_molecule_chembl_id",
    		sort = "drugind_id molecule_chembl_id parent_molecule_chembl_id max_phase_for_ind mesh_id mesh_heading efo_id efo_term",
    		filters = {text = "efo_term efo_id mesh_heading mesh_id", number = "max_phase_for_ind drugind_id",
    			id = "molecule_chembl_id parent_molecule_chembl_id"}},
    	-- Structure searches return molecules and have no get or text search.
    	{name = "Similarity", path = "similarity", rows = "molecules", label = "similarity search", search = false, id = "",
    		about = "", compact = MOLECULE_COMPACT .. " similarity", fields = STRUCTURE_FIELDS .. " similarity",
    		sort = STRUCTURE_SORT .. " similarity", filters = STRUCTURE_FILTERS},
    	{name = "Substructure", path = "substructure", rows = "molecules", label = "substructure search", search = false,
    		id = "", about = "", compact = MOLECULE_COMPACT, fields = STRUCTURE_FIELDS, sort = STRUCTURE_SORT,
    		filters = STRUCTURE_FILTERS},
    } :: {Options}) :: any
    
    local BY_NAME: {[string]: Resource} = {}
    for _, resource in RESOURCES do
    	resource.only = "only=" .. url.encode(table.concat(words(resource.compact), ","))
    	resource.compactSet, resource.fieldSet, resource.sortSet = set(resource.compact), set(resource.fields), set(resource.sort)
    	resource.filterKinds = {}
    	for kind, list in resource.filters do
    		for _, field in words(list) do resource.filterKinds[field] = kind end
    	end
    	BY_NAME[resource.name] = resource
    end
    
    local function finite(value: any): boolean
    	return type(value) == "number" and value == value and math.abs(value) < 2 ^ 53
    end
    
    local function number(value: number): string
    	return if value % 1 == 0 then string.format("%d", value) else tostring(value)
    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 " .. number(minimum) .. " to " .. number(maximum))
    	return value
    end
    
    local function text(value: any, field: string): string
    	assert(type(value) == "string" and value ~= "" and #value <= MAX_TEXT,
    		field .. " must be a nonempty string of at most " .. tostring(MAX_TEXT) .. " bytes")
    	return value
    end
    
    local function chemblId(value: any, field: string): string
    	local id = if type(value) == "string" then string.upper(value) else nil
    	assert(id and string.match(id, CHEMBL_ID), field .. " must be a ChEMBL ID such as CHEMBL25")
    	return id
    end
    
    -- A SMILES string is printable ASCII without spaces.
    local function smiles(value: any, field: string, minimum: number): string
    	assert(type(value) == "string" and #value >= minimum and #value <= MAX_TEXT and string.match(value, "^[%w%p]+$"),
    		field .. " must be a SMILES string of " .. tostring(minimum) .. " to " .. tostring(MAX_TEXT) .. " characters without spaces")
    	return value
    end
    
    -- A list takes an array or one comma-separated string.
    local function list(value: any, field: string, maximum: number): {any}
    	local items: {any} = {}
    	if type(value) == "string" then
    		for item in string.gmatch(value, "[^,]+") do
    			local trimmed = string.match(item, "^%s*(.-)%s*$") :: string
    			if trimmed ~= "" then table.insert(items, trimmed) end
    		end
    	else
    		assert(type(value) == "table", field .. " must be an array or a comma-separated string")
    		for index, item in value do
    			assert(index == #items + 1, field .. " must be a dense array")
    			table.insert(items, item)
    		end
    	end
    	assert(#items > 0 and #items <= maximum, field .. " must list 1 to " .. tostring(maximum) .. " values")
    	return items
    end
    
    -- Names are checked before they appear in an error message.
    local function name(value: any, field: string): string
    	assert(type(value) == "string" and #value <= 100 and string.match(value, "^%-?[%l%d_]+$"),
    		field .. " must contain lowercase ChEMBL field names such as pref_name")
    	return value
    end
    
    local function scalar(value: any, kind: string, key: string): string
    	if kind == "number" then
    		assert(finite(value), key .. " must be a finite number")
    		return number(value)
    	elseif kind == "flag" then
    		assert(type(value) == "boolean" or (finite(value) and value % 1 == 0), key .. " must be true, false or an integer")
    		return if type(value) == "boolean" then tostring(value) else number(value)
    	elseif kind == "id" then
    		return chemblId(value, key)
    	elseif kind == "smiles" then
    		return smiles(value, key, 1)
    	end
    	if finite(value) then return number(value) end
    	return text(value, key)
    end
    
    local function filterParam(resource: Resource, key: any, value: any): string
    	local filter = name(key, "filters")
    	local prefix, suffix = string.match(filter, "^(.-)__(%l+)$")
    	local field: string, lookup: string = filter, "exact"
    	if prefix and suffix and ANY_LOOKUP[suffix] then field, lookup = prefix, suffix end
    	local kind = resource.filterKinds[field]
    	assert(kind, resource.label .. " has no filter " .. filter .. "; help() lists the filters")
    	assert(LOOKUPS[kind][lookup], field .. " accepts only the lookups " .. LOOKUP_LISTS[kind])
    	local rendered
    	if lookup == "isnull" then
    		assert(type(value) == "boolean", key .. " must be true or false")
    		rendered = tostring(value)
    	elseif lookup == "in" or lookup == "range" then
    		local items = list(value, key, if lookup == "range" then 2 else 1000)
    		assert(lookup == "in" or #items == 2, key .. " must be {low, high}")
    		for index, item in items do
    			-- A comma-separated string gives string items; numbers are read back first.
    			if kind == "number" and type(item) == "string" then item = tonumber(item) end
    			items[index] = scalar(item, kind, key)
    			assert(not string.find(items[index], ",", 1, true), key .. " values must not contain commas")
    		end
    		rendered = table.concat(items, ",")
    	else
    		rendered = scalar(value, kind, key)
    	end
    	return key .. "=" .. url.encode(rendered)
    end
    
    -- Returns the only parameter, or nil for complete records, and whether every row field is a compact default.
    local function onlyParam(resource: Resource, value: any): (string?, boolean)
    	if value == "all" then return nil, false end
    	if value == nil then return resource.only, true end
    	local fields = list(value, "fields", 100)
    	local compact = true
    	for _, field in fields do
    		assert(resource.fieldSet[name(field, "fields")], "fields contains " .. field .. ", which is not a " .. resource.label .. " field")
    		compact = compact and resource.compactSet[field] == true
    	end
    	return "only=" .. url.encode(table.concat(fields, ",")), compact
    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
    
    local function errorCode(err: any): any
    	return if type(err) == "table" then err.code else nil
    end
    
    local function failure(operation: string, response: HttpResponse, missing: string?): never
    	local status = response.statusCode
    	local detail = ""
    	if status >= 300 and status < 400 then
    		response.body:close()
    		detail = "unexpected redirect"
    	else
    		-- ChEMBL errors are JSON with error_message and often a long traceback; other bodies are never shown. An error
    		-- body that stalls or breaks counts as empty, within its page's body time.
    		local read, prefix = pcall(function() return await(response.body:readPrefix(64 * 1024), BODY_TIME) end)
    		if not read and errorCode(prefix) == "cancelled" then error(prefix, 0) end
    		local ok, decoded = pcall(json.decode, if read then prefix else "")
    		if ok and type(decoded) == "table" and type(decoded.error_message) == "string" then
    			-- houston.fail repairs a character split by the cut.
    			detail = string.sub(string.match(string.gsub(decoded.error_message, "%s+", " "), "^ ?(.-) ?$") :: string, 1, 300)
    		elseif status == 404 and missing then
    			detail = missing .. " was not found"
    		end
    	end
    	local message = "ChEMBL 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 a 5xx is a server fault unless ChEMBL rejected a query structure it cannot parse.
    	local transient = status == 429 or (status >= 500 and not (string.find(detail, "standardizing the query molecule", 1, true)
    		or string.find(detail, "SanitizeMol", 1, true)))
    	return houston.fail({operation = operation, layer = "upstream", upstream_status = status, retryable = transient,
    		message = message})
    end
    
    -- Returns the decoded JSON object and the bytes read.
    local function fetch(operation: string, target: string, budget: number, time: number, missing: string?): (any, number)
    	local sent, response = pcall(function()
    		return await(http.request({method = "GET", url = target, headers = {Accept = {"application/json"}},
    			timeoutMs = time - BODY_TIME}))
    	end)
    	if not sent then
    		if errorCode(response) ~= "timeout" then error(response, 0) end
    		houston.fail({operation = operation, layer = "upstream", retryable = true,
    			message = "ChEMBL did not answer within " .. tostring((time - BODY_TIME) // 1000) .. " s; retry, since ChEMBL caches results, or narrow the request"})
    	end
    	if response.statusCode ~= 200 then failure(operation, response, missing) end
    	local read, raw = pcall(function() return await(response.body:readAll(budget), BODY_TIME) end)
    	if not read then
    		local code = errorCode(raw)
    		if code == "limit_exceeded" then
    			houston.fail({operation = operation, layer = "upstream", upstream_status = 200, retryable = false,
    				message = "ChEMBL returned more data than one call can hold; request fewer fields" .. (if missing then "" else " or a lower limit")})
    		elseif code == "timeout" then
    			houston.fail({operation = operation, layer = "upstream", upstream_status = 200, retryable = true,
    				message = "ChEMBL did not finish sending its answer within " .. tostring(BODY_TIME // 1000) .. " s; retry, or request fewer rows or fields"})
    		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)
    		houston.fail({operation = operation, layer = "upstream", upstream_status = 200, retryable = true,
    			message = "ChEMBL response failed: " .. string.sub(detail, 1, 300)})
    	end
    	local ok, value = pcall(json.decode, raw)
    	if not ok or type(value) ~= "table" or not string.match(raw, "^%s*{") then
    		houston.fail({operation = operation, layer = "upstream", upstream_status = 200, retryable = false,
    			message = "ChEMBL returned an invalid JSON object"})
    	end
    	return value, #raw
    end
    
    -- Searches and lists: one fixed query, read page by page within the row limit, byte budget and time limit.
    local function collect(operation: string, resource: Resource, args: Options, query: {string}): Options
    	local limit = integer(if args.limit == nil then DEFAULT_LIMIT else args.limit, "limit", 1, MAX_LIMIT)
    	local offset = integer(if args.offset == nil then 0 else args.offset, "offset", 0, MAX_OFFSET)
    	args.limit, args.offset = nil, nil
    	local path = resource.path
    	if args.q ~= nil then
    		assert(resource.search, operation .. " has no q text search; use filters")
    		table.insert(query, "q=" .. url.encode(text(args.q, "q")))
    		path ..= "/search"
    		args.q = nil
    	end
    	if args.filters ~= nil then
    		assert(type(args.filters) == "table", "filters must be a table of field__lookup = value")
    		for key, value in args.filters do table.insert(query, filterParam(resource, key, value)) end
    		args.filters = nil
    	end
    	table.sort(query)
    	if args.order_by ~= nil then
    		for _, key in list(args.order_by, "order_by", MAX_SORT) do
    			assert(resource.sortSet[string.gsub(name(key, "order_by"), "^%-", "")],
    				"order_by contains " .. key .. ", which cannot sort " .. resource.label .. " results; help() lists the sort fields")
    			table.insert(query, "order_by=" .. url.encode(key))
    		end
    		args.order_by = nil
    	end
    	local only, compact = onlyParam(resource, args.fields)
    	args.fields = nil
    	if only then table.insert(query, only) end
    	noneLeft(args, operation)
    	local base = API .. "/" .. path .. ".json?" .. (if #query > 0 then table.concat(query, "&") .. "&" else "")
    	assert(#base + PAGING_BYTES <= MAX_URL, "the request is too long: " .. tostring(#base + PAGING_BYTES)
    		.. " bytes once URL-encoded, at most " .. tostring(MAX_URL) .. "; use fewer or shorter values")
    
    	local rows = json.decode("[]")
    	local result: Options = {[resource.rows] = rows}
    	local used, more = 0, false
    	for page = 1, MAX_PAGES do
    		local size = math.min(limit - #rows, PAGE_SIZE)
    		if page == 1 then
    			size = math.min(size, MAX_BYTES // (if compact then COMPACT_ROW else FULL_ROW))
    		else
    			-- Size later pages from the bytes per row so far, so they fit the remaining budget.
    			size = math.min(size, (MAX_BYTES - used) // (2 * used / #rows))
    			if size < 1 then break end
    		end
    		local read, body, bytes = pcall(function(): (any, number)
    			local value, length = fetch(operation, base .. "limit=" .. tostring(size) .. "&offset=" .. tostring(offset + #rows),
    				MAX_BYTES - used, if page == 1 then CALL_TIME - LATER_TIME else LATER_TIME)
    			if type(value[resource.rows]) ~= "table" or type(value.page_meta) ~= "table" or not finite(value.page_meta.total_count) then
    				houston.fail({operation = operation, layer = "upstream", upstream_status = 200, retryable = false,
    					message = "ChEMBL returned an unexpected " .. resource.label .. " page"})
    			end
    			return value, length
    		end)
    		if not read then
    			-- Any failure after the first page ends the call with the rows so far; the caller continues from next_offset.
    			if page == 1 or errorCode(body) == "cancelled" then error(body, 0) end
    			break
    		end
    		used += bytes
    		local found, meta = body[resource.rows], body.page_meta
    		if page == 1 then result.total_count = meta.total_count end
    		for _, row in found do table.insert(rows, row) end
    		-- ChEMBL links the next page while rows remain after this one.
    		more = #found > 0 and type(meta.next) == "string"
    		if not more or #rows >= limit then break end
    	end
    	if more then result.next_offset = offset + #rows end
    	return result
    end
    
    local function get(resource: Resource): (any, Options?) -> any
    	local operation = "get" .. resource.name
    	return function(value: any, input: Options?): any
    		local args = options(input, operation)
    		local id
    		if resource.id == "integer" then
    			id = number(integer(if type(value) == "string" and string.match(value, "^%d+$") then tonumber(value) else value,
    				"id", 1, 2 ^ 53 - 1))
    		elseif resource.id == "molecule" then
    			id = if type(value) == "string" then string.upper(value) else ""
    			assert(string.match(id, INCHIKEY) or string.match(id, CHEMBL_ID),
    				"id must be a ChEMBL ID such as CHEMBL25 or a standard InChIKey")
    		else
    			id = chemblId(value, "id")
    		end
    		local only = if args.fields == nil then nil else onlyParam(resource, args.fields)
    		args.fields = nil
    		noneLeft(args, operation)
    		local target = API .. "/" .. resource.path .. "/" .. id .. ".json" .. (if only then "?" .. only else "")
    		assert(#target <= MAX_URL, "fields is too long once URL-encoded, at most " .. tostring(MAX_URL) .. " bytes")
    		return (fetch(operation, target, MAX_BYTES, CALL_TIME, resource.label .. " " .. id))
    	end
    end
    
    -- The query molecule is a SMILES string or a ChEMBL ID, under ChEMBL's own parameter names.
    local function structure(operation: string, args: Options, minimum: number): {string}
    	assert((args.smiles == nil) ~= (args.chembl_id == nil), operation .. " takes either smiles or chembl_id")
    	local query = if args.smiles ~= nil then "smiles=" .. url.encode(smiles(args.smiles, "smiles", minimum))
    		else "chembl_id=" .. chemblId(args.chembl_id, "chembl_id")
    	args.smiles, args.chembl_id = nil, nil
    	return {query}
    end
    
    local function similarMolecules(input: Options?): Options
    	local args = options(input, "similarMolecules")
    	local query = structure("similarMolecules", args, 1)
    	local similarity = integer(if args.similarity == nil then DEFAULT_SIMILARITY else args.similarity, "similarity",
    		MIN_SIMILARITY, 100)
    	args.similarity = nil
    	table.insert(query, "similarity=" .. number(similarity))
    	return collect("similarMolecules", BY_NAME.Similarity, args, query)
    end
    
    local function substructureMolecules(input: Options?): Options
    	local args = options(input, "substructureMolecules")
    	return collect("substructureMolecules", BY_NAME.Substructure, args, structure("substructureMolecules", args, MIN_SUBSTRUCTURE))
    end
    
    local exports: {[string]: any} = {similarMolecules = similarMolecules, substructureMolecules = substructureMolecules}
    local sections: {string} = {}
    
    local function listHelp(lists: {[string]: string}): string
    	local parts: {string} = {}
    	for _, kind in KINDS do
    		if lists[kind] then table.insert(parts, kind .. ": " .. string.gsub(lists[kind], " ", ", ")) end
    	end
    	return table.concat(parts, "; ")
    end
    
    local function filterHelp(resource: Resource): string
    	return "Filters by kind: " .. listHelp(resource.filters) .. ".\norder_by: "
    		.. string.gsub(resource.sort, " ", ", ") .. ".\nfields: " .. string.gsub(resource.fields, " ", ", ")
    		.. ". Default fields: " .. string.gsub(resource.compact, " ", ", ") .. "."
    end
    
    for _, resource in RESOURCES do
    	if resource.id ~= "" then
    		local listName = "search" .. string.gsub(string.gsub(resource.rows, "^%l", string.upper), "_(%l)", string.upper)
    		exports[listName] = function(input: Options?): Options
    			return collect(listName, resource, options(input, listName), {})
    		end
    		exports["get" .. resource.name] = get(resource)
    		table.insert(sections, "## " .. listName .. "(opts?) and get" .. resource.name .. "(id, opts?)\n\n"
    			.. "GET /" .. resource.path .. (if resource.search then " (with q: /" .. resource.path .. "/search)" else "")
    			.. " and /" .. resource.path .. "/{id}. Rows come back as `" .. resource.rows .. "`. " .. resource.about
    			.. (if resource.search then "" else " No q text search.") .. "\n" .. filterHelp(resource))
    	end
    end
    
    local HELP = [[ChEMBL: search and read EMBL-EBI's open database of bioactive molecules, their targets, measured bioactivities, assays, source documents, drug mechanisms and indications (ChEMBL data web services, https://www.ebi.ac.uk/chembl/api/data/docs). No account or credentials. Read-only. Calls return completed values; do not wrap them in await(). Records keep ChEMBL's JSON field names and values unchanged; decimals such as max_phase, alogp, standard_value and pchembl_value come back as strings. Data is CC BY-SA 3.0: credit "ChEMBL, EMBL-EBI" when presenting results.
    
    ## Searches: search<Rows>(opts?), similarMolecules(opts), substructureMolecules(opts)
    
    Return `{<rows>, total_count, next_offset?}`, for example `{molecules = {...100 rows}, total_count = 2921148, next_offset = 100}` for the default limit of 100 from offset 0. Options use ChEMBL's names; unknown options, filters, lookups, sort fields and field names are rejected before any request, because ChEMBL itself silently ignores unknown filters and returns every record.
    - q: free text, for searches that support it; results rank by relevance unless order_by is given. ChEMBL counts at most 10,000 text matches.
    - filters: a table of `field__lookup = value`, all of which must match, such as `{pref_name__icontains = "statin", max_phase = 4, ["molecule_properties__full_mwt__lte"] = 500}`. A bare field means exact. `in` takes an array (values without commas), `range` takes {low, high}, `isnull` takes true or false. Each resource below lists its filters by kind. Lookups by kind: ]] .. listHelp(LOOKUP_LISTS) .. [[. text and term values are strings, number values numbers, flag values true, false or an integer, id values ChEMBL IDs and smiles values SMILES strings.
    - order_by: a field, or -field for descending, or an array of up to 3. Descending order puts missing values first; add a filter such as `pchembl_value__isnull = false`.
    - fields: an array or comma-separated string of top-level fields for each row, or "all" for complete records. Defaults to the compact fields listed per resource. A nested object such as molecule_properties comes back whole.
    - limit: rows to return, 1 to 2000 (default 100). offset: rows to skip (default 0).
    next_offset is present exactly when ChEMBL has rows after the last one returned: call again with the same options and offset = next_offset. A call reads at most two ChEMBL pages of up to 1,000 rows and 4 MiB, so it may return fewer than limit rows with next_offset; fields beyond the defaults, or "all", start with a first page of 32 rows.
    
    ## similarMolecules({smiles | chembl_id, similarity?, filters?, order_by?, fields?, limit?, offset?})
    
    GET /similarity. Molecules whose Tanimoto similarity to the query structure is at least similarity percent, 40 to 100 (default 80). Each row adds `similarity`, a string percentage; rows come highest first. A chembl_id query excludes that molecule itself; a smiles query includes it. Filters, order_by and fields are those of searchMolecules except the molecule_synonyms ones, plus similarity.
    
    ## substructureMolecules({smiles | chembl_id, filters?, order_by?, fields?, limit?, offset?})
    
    GET /substructure. Molecules containing the query structure; smiles has at least 5 characters, and ChEMBL stops at 30,000 matches. Filters, order_by and fields are those of searchMolecules except the molecule_synonyms ones.
    
    ## get<Name>(id, opts?)
    
    Returns one complete record; opts.fields selects top-level fields as in the searches. An unknown ID fails with HTTP 404.
    
    ]]
    
    local HELP_END = [[
    
    
    ## Errors and limits
    
    Invalid input fails before any request, including requests over 4,000 bytes once URL-encoded (SMILES strings count once encoded). ChEMBL errors come back as upstream errors with the HTTP status and ChEMBL's message, such as a SMILES string it cannot parse (HTTP 500, not retryable). HTTP 429 and other 5xx errors are retryable. ChEMBL answers a cached query in about a second and a new one in 5 to 15 s or more. Houston ends a call after 30 s, so a call gives ChEMBL 27 s: 18 s for the first page and 9 s for the second, each including 3 s to receive the body; a record read gets all 27 s. A first page or record that runs out of time fails as retryable (ChEMBL caches results, so a retry is often fast). A second page that runs out of time or fails for any other reason ends the call with the rows so far and next_offset. Prefer narrow filters and compact fields over many calls.
    
    ## Example
    
    Here chembl is the configured ChEMBL connection.
    
    ```lua
    local found = chembl.searchMolecules({q = "imatinib", fields = {"molecule_chembl_id", "pref_name", "max_phase"}, limit = 5})
    local id = found.molecules[1].molecule_chembl_id
    local potent = chembl.searchActivities({filters = {molecule_chembl_id = id, standard_type__in = {"IC50", "Ki"},
    	pchembl_value__gte = 7}, order_by = "-pchembl_value", limit = 200})
    for _, row in potent.activities do print(row.target_pref_name, row.standard_type, row.pchembl_value) end
    local moa = chembl.searchMechanisms({filters = {parent_molecule_chembl_id = id}})
    local close = chembl.similarMolecules({smiles = "CC(=O)Oc1ccccc1C(=O)O", similarity = 70, filters = {max_phase = 4}})
    local target = chembl.getTarget("CHEMBL203")
    ```]]
    
    local function help(): string
    	return HELP .. table.concat(sections, "\n\n") .. HELP_END
    end
    
    exports.help = help
    return exports
    
  • houston.json
    {
      "schema_version": 2,
      "name": "ChEMBL",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "proxy": [
        {
          "match": {
            "protocol": "http",
            "host": [
              "www.ebi.ac.uk"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/chembl/api/data/molecule.json",
              "/chembl/api/data/molecule/{id}",
              "/chembl/api/data/target.json",
              "/chembl/api/data/target/{id}",
              "/chembl/api/data/activity.json",
              "/chembl/api/data/activity/{id}",
              "/chembl/api/data/assay.json",
              "/chembl/api/data/assay/{id}",
              "/chembl/api/data/document.json",
              "/chembl/api/data/document/{id}",
              "/chembl/api/data/mechanism.json",
              "/chembl/api/data/mechanism/{id}",
              "/chembl/api/data/drug_indication.json",
              "/chembl/api/data/drug_indication/{id}",
              "/chembl/api/data/similarity.json",
              "/chembl/api/data/substructure.json"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization",
                "Cookie"
              ]
            }
          }
        }
      ]
    }
    
  • icon.svgicon.svg
  • README.md
    ---
    description: Search ChEMBL's open database of bioactive molecules, drug targets, bioactivity measurements, drug mechanisms and indications.
    ---
    
    # ChEMBL
    
    Let agents search molecules, similar structures, drug targets and bioactivity
    measurements, and read the assays, publications, mechanisms and indications behind
    them. Access is read-only and requires no account.
    
    > ChEMBL data uses [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/).
    > Credit ChEMBL and EMBL-EBI, and share adapted data under the same licence.
    
    [EMBL-EBI's terms](https://www.ebi.ac.uk/about/terms-of-use) apply.
    This connector is not affiliated with EMBL-EBI.
    
    [Add ChEMBL](SETUP.md).
    
  • SETUP.md
    # Add ChEMBL
    
    Select **Add connection** in Houston. No account, API key or settings are required.
    
    For a missing molecule, search by name to find its ChEMBL ID. Structure searches
    need valid SMILES; substructures need at least five characters.
    
    [ChEMBL web services](https://chembl.gitbook.io/chembl-interface-documentation/web-services/chembl-data-web-services).
    
  • tests
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = {},
      				config = {},
      				endpoint = { "GET", "https://www.ebi.ac.uk/chembl/api/data/molecule.json" },
      				expected = "",
      				header = "Authorization",
      				method = "",
      				publisher = {},
      			},
      		})
      	end,
      }
      
    • errors.luau
      -- Invalid input never reaches the network; ChEMBL errors, slow answers and bad pages map to clear failures.
      return {
      	scenario = {publisher = {}, config = {}, auth_method = "", auth_config = {}},
      	configure = function()
      		calls = 0
      		status = 200
      		payload = "{}"
      		responseHeaders = {}
      		http = {request = function()
      			calls += 1
      			-- 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(chembl)
      		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 ChEMBL")
      		end
      		local function molecules(opts) return function() chembl.searchMolecules(opts) end end
      
      		rejected(function() chembl.searchMolecules("aspirin") end, "options must be a table")
      		rejected(molecules({search = "aspirin"}), "unknown option search")
      		rejected(molecules({only = "pref_name"}), "unknown option only")
      		rejected(molecules({q = ""}), "q must be a nonempty string")
      		rejected(molecules({q = string.rep("a", 1001)}), "at most 1000 bytes")
      		rejected(function() chembl.searchMechanisms({q = "EGFR"}) end, "searchMechanisms has no q text search")
      		rejected(molecules({filters = "max_phase=4"}), "filters must be a table")
      		-- ChEMBL ignores unknown filters and answers with every molecule, so they never reach it.
      		rejected(molecules({filters = {foo = 1}}), "molecule has no filter foo")
      		rejected(molecules({filters = {pref_name__bogus = "x"}}), "molecule has no filter pref_name__bogus")
      		rejected(molecules({filters = {molecule_synonyms__syn_type = "x"}}), "has no filter molecule_synonyms__syn_type")
      		rejected(function() chembl.substructureMolecules({smiles = "c1ccccc1", filters = {molecule_synonyms__molecule_synonym = "x"}}) end,
      			"substructure search has no filter")
      		rejected(molecules({filters = {["Pref_Name"] = "x"}}), "lowercase ChEMBL field names")
      		rejected(molecules({filters = {[1] = "x"}}), "lowercase ChEMBL field names")
      		rejected(molecules({filters = {max_phase__icontains = "4"}}), "max_phase accepts only the lookups exact gt gte")
      		rejected(molecules({filters = {oral__gte = 1}}), "oral accepts only the lookups exact isnull")
      		rejected(molecules({filters = {molecule_structures__canonical_smiles = "CCO"}}), "accepts only the lookups flexmatch connectivity")
      		rejected(molecules({filters = {max_phase = "4"}}), "max_phase must be a finite number")
      		rejected(molecules({filters = {oral = "yes"}}), "oral must be true, false or an integer")
      		rejected(molecules({filters = {pref_name = true}}), "pref_name must be a nonempty string")
      		rejected(molecules({filters = {pref_name = ""}}), "pref_name must be a nonempty string")
      		rejected(molecules({filters = {molecule_chembl_id = "25"}}), "molecule_chembl_id must be a ChEMBL ID")
      		rejected(molecules({filters = {pref_name__isnull = "false"}}), "pref_name__isnull must be true or false")
      		rejected(molecules({filters = {molecule_chembl_id__in = {}}}), "must list 1 to 1000 values")
      		rejected(molecules({filters = {molecule_chembl_id__in = {[1] = "CHEMBL25", [3] = "CHEMBL2"}}}), "must be a dense array")
      		rejected(molecules({filters = {pref_name__in = {"A, B"}}}), "values must not contain commas")
      		rejected(molecules({filters = {max_phase__range = {1, 2, 3}}}), "must list 1 to 2 values")
      		rejected(molecules({filters = {max_phase__range = {1}}}), "must be {low, high}")
      		rejected(molecules({filters = {max_phase__in = "3,x"}}), "max_phase__in must be a finite number")
      		rejected(molecules({filters = {molecule_structures__canonical_smiles__flexmatch = "C C"}}), "without spaces")
      		rejected(molecules({order_by = "score"}), "order_by contains score, which cannot sort molecule results")
      		rejected(molecules({order_by = "--pref_name"}), "lowercase ChEMBL field names")
      		rejected(molecules({order_by = {"pref_name", "max_phase", "usan_year", "molecule_type"}}), "order_by must list 1 to 3")
      		rejected(molecules({order_by = "similarity"}), "cannot sort molecule results")
      		rejected(molecules({fields = {"score"}}), "fields contains score, which is not a molecule field")
      		rejected(molecules({fields = "pref_name,bogus"}), "fields contains bogus")
      		rejected(molecules({fields = {}}), "fields must list 1 to 100")
      		rejected(function() chembl.substructureMolecules({smiles = "c1ccccc1", fields = "molecule_synonyms"}) end,
      			"not a substructure search field")
      		for _, limit in {0, 2001, 1.5, "10", false} do
      			rejected(molecules({limit = limit}), "limit must be an integer from 1 to 2000")
      		end
      		for _, offset in {-1, 0.5, 2 ^ 31} do
      			rejected(molecules({offset = offset}), "offset must be an integer from 0 to 2147483647")
      		end
      		rejected(molecules({filters = {molecule_chembl_id__in = table.create(400, "CHEMBL1234567")}}), "the request is too long")
      
      		rejected(function() chembl.similarMolecules() end, "similarMolecules takes either smiles or chembl_id")
      		rejected(function() chembl.similarMolecules({smiles = "CCO", chembl_id = "CHEMBL25"}) end, "takes either smiles or chembl_id")
      		rejected(function() chembl.similarMolecules({smiles = "CCO", similarity = 39}) end, "similarity must be an integer from 40 to 100")
      		rejected(function() chembl.similarMolecules({smiles = "CCO", similarity = 101}) end, "from 40 to 100")
      		rejected(function() chembl.similarMolecules({smiles = "C C O"}) end, "smiles must be a SMILES string")
      		rejected(function() chembl.similarMolecules({smiles = "CCO\n"}) end, "without spaces")
      		rejected(function() chembl.similarMolecules({chembl_id = "aspirin"}) end, "chembl_id must be a ChEMBL ID")
      		rejected(function() chembl.similarMolecules({smiles = "CCO", q = "x"}) end, "has no q text search")
      		rejected(function() chembl.substructureMolecules({smiles = "CCCC"}) end, "smiles must be a SMILES string of 5 to 1000")
      
      		for _, id in {"CHEMBL", "CHEMBL25/../x", "25", "", 25, "BSYNRYMUTXBXSQ-UHFFFAOYSA", "BSYNRYMUTXBXSQ-UHFFFAOYSA-N/x"} do
      			rejected(function() chembl.getMolecule(id) end, "id must be a ChEMBL ID such as CHEMBL25 or a standard InChIKey")
      		end
      		rejected(function() chembl.getTarget("BSYNRYMUTXBXSQ-UHFFFAOYSA-N") end, "id must be a ChEMBL ID such as CHEMBL25")
      		rejected(function() chembl.getTarget() end, "id must be a ChEMBL ID")
      		for _, id in {0, -1, 1.5, "12a", "", "CHEMBL25", 2 ^ 53} do
      			rejected(function() chembl.getActivity(id) end, "id must be an integer from 1 to")
      		end
      		rejected(function() chembl.getMolecule("CHEMBL25", {only = "pref_name"}) end, "getMolecule received an unknown option only")
      		rejected(function() chembl.getMolecule("CHEMBL25", {fields = "score"}) end, "fields contains score")
      		rejected(function() chembl.getMolecule("CHEMBL25", "all") end, "getMolecule options must be a table")
      
      		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 search = molecules({q = "aspirin"})
      		local function similar() chembl.similarMolecules({smiles = "C1CC1C(", similarity = 70}) end
      		local function read() chembl.getMolecule("CHEMBL999999999") end
      		local traceback = ', "traceback": "Traceback (most recent call last):\\n  File \\"/chembl_ws_py3/src/resource.py\\""}'
      
      		upstream(400, '{"error_message": "No search query provided"}', {}, search,
      			{"ChEMBL HTTP 400: No search query provided", '"retryable":false'})
      		upstream(500, '{"error_message": "Problem standardizing the query molecule"' .. traceback, {}, similar,
      			{"ChEMBL HTTP 500: Problem standardizing the query molecule", '"retryable":false'}, "Traceback")
      		upstream(500, '{"error_message": "Python argument types in\\n    rdkit.Chem.rdmolops.SanitizeMol(NoneType)"' .. traceback, {}, similar,
      			{"HTTP 500: Python argument types in rdkit.Chem.rdmolops.SanitizeMol(NoneType)", '"retryable":false'}, "chembl_ws_py3")
      		-- Other 500s, even with a message, are backend faults such as a database timeout.
      		upstream(500, '{"error_message": "canceling statement due to statement timeout"' .. traceback, {}, search,
      			{"HTTP 500: canceling statement due to statement timeout", '"retryable":true'}, "Traceback")
      		upstream(400, '{"error_message": "' .. string.rep("y", 1000) .. '"}', {}, search, {"HTTP 400: " .. string.rep("y", 300)}, string.rep("y", 301))
      		upstream(400, '{"error_message": "' .. string.rep("y", 299) .. 'é"}', {}, search, {"HTTP 400: " .. string.rep("y", 299)})
      		upstream(404, "", {}, read, {"ChEMBL HTTP 404: molecule CHEMBL999999999 was not found", '"retryable":false'})
      		upstream(404, "<!DOCTYPE html><html><title>Page not found at /chembl/api/data/x</title>" .. string.rep("<p>urlconf</p>", 9000), {}, read,
      			{"HTTP 404: molecule CHEMBL999999999 was not found"}, "urlconf")
      		upstream(404, '{"error_message": "Couldn\'t find an instance of \'MoleculeDictionary\' which matched \'chembl_id=[\'CHEMBL9\']\'."' .. traceback, {},
      			function() chembl.similarMolecules({chembl_id = "CHEMBL9"}) end, {"HTTP 404: Couldn't find an instance of 'MoleculeDictionary'"}, "Traceback")
      		upstream(500, "<html><body>Internal Server Error</body></html>", {}, search, {"ChEMBL HTTP 500", '"retryable":true'}, "Internal")
      		upstream(502, "", {}, search, {"ChEMBL HTTP 502", '"retryable":true'})
      		upstream(504, '{"error_message": "timeout"}', {}, read, {"HTTP 504: timeout", '"retryable":true'})
      		upstream(429, "Too Many Requests", {["retry-after"] = {"7"}}, search, {"HTTP 429", "retry after 7s", '"retryable":true'}, "Too Many")
      		upstream(503, "", {["retry-after"] = {"Thu, 29 Oct 2026 20:00:00 GMT"}}, search,
      			{"retry after Thu, 29 Oct 2026 20:00:00 GMT", '"retryable":true'}, "GMTs")
      		upstream(301, "", {location = {"https://www.ebi.ac.uk/chembl/ws"}}, read, {"HTTP 301: unexpected redirect", '"retryable":false'}, "/ws")
      		upstream(200, "<?xml version='1.0'?><response/>", {}, read, {"invalid JSON object", '"retryable":false'})
      		upstream(200, "[]", {}, search, {"invalid JSON object"})
      		upstream(200, '{"molecules": {}, "page_meta": null}', {}, search, {"unexpected molecule page", '"retryable":false'})
      		upstream(200, '{"targets": [], "page_meta": {"total_count": 0}}', {}, search, {"unexpected molecule page"})
      		upstream(200, '{"molecules": [], "page_meta": {"total_count": "3"}}', {}, search, {"unexpected molecule page"})
      		upstream(200, '{"x":"' .. string.rep("z", 4 * 1024 * 1024) .. '"}', {}, read,
      			{"more data than one call can hold; request fewer fields", '"retryable":false'}, "limit")
      		upstream(200, '{"molecules":[],"x":"' .. string.rep("z", 4 * 1024 * 1024) .. '"}', {}, search, {"more data than one call can hold; request fewer fields or a lower limit"})
      
      		requestError = {code = "timeout", message = "request deadline"}
      		upstream(200, "", {}, search, {"ChEMBL did not answer within 15 s", '"retryable":true'})
      		upstream(200, "", {}, read, {"did not answer within 24 s"})
      		-- Other request failures pass through unchanged, message included, and never become an upstream failure.
      		requestError = {code = "access_denied", message = "origin not allowed"}
      		upstream(200, "", {}, read, {"origin not allowed"}, "retryable")
      		requestError = nil
      		-- The body read has its own share of the call's time.
      		readError = {code = "timeout", message = "await timed out"}
      		upstream(200, "", {}, search, {"ChEMBL did not finish sending its answer within 3 s", '"retryable":true'})
      		readError = {code = "io_error", message = "connection reset by peer"}
      		upstream(200, "", {}, search, {"ChEMBL response failed: connection reset by peer", '"retryable":true'}, "more data")
      		-- An error body that stalls or breaks still gives the structured failure.
      		upstream(503, "", {}, search, {"ChEMBL HTTP 503", '"retryable":true', '"upstream_status":503'}, "reset")
      		readError = {code = "timeout", message = "await timed out"}
      		upstream(400, "", {}, read, {"ChEMBL HTTP 400", '"retryable":false', '"upstream_status":400'}, "timed out")
      		readError = {code = "cancelled", message = "invocation cancelled"}
      		local before = calls
      		local ok, err = pcall(read)
      		-- 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)
      		-- TestChEMBLPublicReadRoutes
      		do
      			local r, err = m.resolve(nil, nil, nil, "")
      			assert(not err, tostring(err))
      			local api = "https://www.ebi.ac.uk/chembl/api/data"
      			for _, route in
      				{
      					"GET "
      						.. api
      						.. "/molecule.json?pref_name__icontains=aspirin&only=molecule_chembl_id&limit=1000&offset=0",
      					"GET " .. api .. "/molecule/search.json?q=aspirin",
      					"GET " .. api .. "/molecule/CHEMBL25.json",
      					"GET " .. api .. "/target/CHEMBL203.json?only=target_chembl_id",
      					"GET " .. api .. "/activity/31863.json",
      					"GET " .. api .. "/drug_indication.json?molecule_chembl_id=CHEMBL25",
      					"GET "
      						.. api
      						.. "/similarity.json?smiles=CC%28%3DO%29Oc1ccccc1C%28%3DO%29O&similarity=80",
      					"GET " .. api .. "/substructure.json?smiles=C%23CC%2FC%3DC%5Cc1ccccc1",
      				}
      			do
      				m.routes(r, "", true, { route })
      			end
      			m.routes(r, "", false, {
      				"POST " .. api .. "/similarity.json",
      				"POST " .. api .. "/molecule.json",
      				"DELETE " .. api .. "/molecule/CHEMBL25.json",
      				"GET " .. api .. "/molecule/set/CHEMBL25;CHEMBL2.json",
      				"GET " .. api .. "/similarity/CCO/80.json",
      				"GET " .. api .. "/status.json",
      				"GET " .. api .. "/chembl_id_lookup/CHEMBL25.json",
      				"GET " .. api .. "/image/CHEMBL25",
      				"GET " .. api .. "/molecule/%2e%2e/status.json",
      				"GET https://www.ebi.ac.uk/ebisearch/ws/rest/chembl",
      				"GET https://ebi.ac.uk/chembl/api/data/molecule.json",
      				"GET https://www.ebi.ac.uk.example.com/chembl/api/data/molecule.json",
      				"GET http://www.ebi.ac.uk:8080/chembl/api/data/molecule.json",
      			})
      		end
      		-- TestChEMBLRejectsMethodOverridesAndDropsCredentials
      		do
      			local r, err = m.resolve(nil, nil, nil, "")
      			assert(not err, tostring(err))
      			local recipe, err = m.recipe(r, "GET", "https://www.ebi.ac.uk/chembl/api/data/molecule.json", nil)
      			assert(not err, tostring(err))
      			m.rejectPreparedOverrides(recipe, r.Context, "GET molecule.json")
      			local dropped = { "Authorization", "Cookie" }
      			local caller = { Accept = { "application/json" } }
      			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, "Accept") ~= "application/json") then
      				m.fail("prepare: %s %s", headers, err)
      			end
      			for _, name in dropped do
      				if m.header(headers, name) ~= "" then
      					m.fail("%s reached ChEMBL", name)
      				end
      			end
      		end
      	end,
      }
      
    • reads.luau
      -- Searches build exact ChEMBL queries and page within one call; records are read by ID.
      return {
      	scenario = {publisher = {}, config = {}, auth_method = "", auth_config = {}},
      	configure = function()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(req.method == "GET" and req.body == nil, "ChEMBL reads must be bodiless GETs")
      			assert(req.headers.Authorization == nil, "the public API takes no credentials")
      			assert(req.headers.Accept[1] == "application/json")
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local queued = table.remove(responses, 1)
      			if type(queued) == "string" then
      				return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(queued)})
      			end
      			-- A table with a code fails while waiting for headers, such as a timeout; one with a status answers with it;
      			-- one with readError has a body whose read fails.
      			if queued.code then error(queued, 0) end
      			local body = if queued.readError
      				then {readAll = function() error(queued.readError, 0) end, readPrefix = function() error(queued.readError, 0) end, close = function() end}
      				else fixture.reader(queued.body or "")
      			return fixture.operation({statusCode = queued.status or 200, headers = {}, body = body})
      		end}
      		function respond(body) table.insert(responses, body) end
      		-- One ChEMBL page: rows are JSON texts, and more links a next page.
      		function page(key, rows, total, more)
      			return '{"' .. key .. '":[' .. table.concat(rows, ",") .. '],"page_meta":{"limit":20,"next":'
      				.. (if more then '"/chembl/api/data/next"' else "null") .. ',"offset":0,"previous":null,"total_count":'
      				.. tostring(total) .. "}}"
      		end
      		function molecules(from, count, padding)
      			local rows = {}
      			for i = from, from + count - 1 do
      				table.insert(rows, '{"molecule_chembl_id":"CHEMBL' .. i .. '"' .. (if padding then ',"p":"' .. string.rep("x", padding) .. '"' else "") .. "}")
      			end
      			return rows
      		end
      	end,
      	run = function(chembl)
      		local API = "https://www.ebi.ac.uk/chembl/api/data"
      		local MOLECULE = "only=molecule_chembl_id%2Cpref_name%2Cmax_phase%2Cmolecule_type%2Cfirst_approval%2Cmolecule_properties"
      		local function url(i) return requests[i or #requests].url end
      
      		local names = {}
      		for name, fn in chembl do
      			assert(type(fn) == "function")
      			table.insert(names, name)
      		end
      		table.sort(names)
      		assert(table.concat(names, ",") == "getActivity,getAssay,getDocument,getDrugIndication,getMechanism,getMolecule,getTarget,"
      			.. "searchActivities,searchAssays,searchDocuments,searchDrugIndications,searchMechanisms,searchMolecules,searchTargets,"
      			.. "similarMolecules,substructureMolecules", table.concat(names, ","))
      		assert(#requests == 0, "initialization reached ChEMBL")
      
      		-- Default search: compact fields, default limit, one page when ChEMBL links no next page.
      		respond(page("molecules", molecules(1, 2), 2, false))
      		local found = chembl.searchMolecules()
      		assert(url() == API .. "/molecule.json?" .. MOLECULE .. "&limit=100&offset=0", url())
      		assert(requests[1].timeoutMs == 15000, "the first page waits 15 s for headers")
      		assert(#found.molecules == 2 and found.molecules[2].molecule_chembl_id == "CHEMBL2")
      		assert(found.total_count == 2 and found.next_offset == nil)
      
      		-- Text search with every filter kind: filters sorted and encoded, order_by kept in order, then fields.
      		local opts = {q = "aspirin", filters = {max_phase = 4, molecule_properties__full_mwt__range = {100, 200.5},
      			pref_name__isnull = false, molecule_chembl_id__in = "chembl25, CHEMBL2", oral = true,
      			molecule_structures__canonical_smiles__flexmatch = "C#N", molecule_synonyms__molecule_synonym__iexact = "Aspirin 81",
      			atc_classifications__level5 = "N02BA01", availability_type__in = {1, 2}, first_approval__range = "1990, 2000.5"},
      			order_by = {"-max_phase", "pref_name"}, fields = "molecule_chembl_id,pref_name", limit = 5, offset = 10}
      		respond(page("molecules", molecules(25, 1), 1, false))
      		found = chembl.searchMolecules(opts)
      		assert(url() == API .. "/molecule/search.json?atc_classifications__level5=N02BA01&availability_type__in=1%2C2"
      			.. "&first_approval__range=1990%2C2000.5&max_phase=4&molecule_chembl_id__in=CHEMBL25%2CCHEMBL2&molecule_properties__full_mwt__range=100%2C200.5"
      			.. "&molecule_structures__canonical_smiles__flexmatch=C%23N&molecule_synonyms__molecule_synonym__iexact=Aspirin%2081"
      			.. "&oral=true&pref_name__isnull=false&q=aspirin&order_by=-max_phase&order_by=pref_name"
      			.. "&only=molecule_chembl_id%2Cpref_name&limit=5&offset=10", url())
      		assert(#found.molecules == 1 and found.next_offset == nil)
      		assert(opts.limit == 5 and opts.filters.max_phase == 4 and opts.fields == "molecule_chembl_id,pref_name",
      			"caller options were modified")
      
      		-- Other resources keep their own row keys and compact fields; empty results stay arrays.
      		respond(page("activities", {}, 0, false))
      		found = chembl.searchActivities({filters = {target_chembl_id = "CHEMBL203", standard_type__in = {"IC50", "Ki"},
      			pchembl_value__gte = 7, potential_duplicate = 0}, order_by = "-pchembl_value"})
      		assert(url() == API .. "/activity.json?pchembl_value__gte=7&potential_duplicate=0&standard_type__in=IC50%2CKi"
      			.. "&target_chembl_id=CHEMBL203&order_by=-pchembl_value&only=activity_id%2Cmolecule_chembl_id%2Cmolecule_pref_name"
      			.. "%2Ctarget_chembl_id%2Ctarget_pref_name%2Ctarget_organism%2Cassay_chembl_id%2Cassay_type%2Cdocument_chembl_id"
      			.. "%2Cstandard_type%2Cstandard_relation%2Cstandard_value%2Cstandard_units%2Cpchembl_value&limit=100&offset=0", url())
      		assert(json.encode(found.activities) == "[]" and found.total_count == 0 and found.next_offset == nil)
      		respond(page("targets", {'{"target_chembl_id":"CHEMBL203"}'}, 1, false))
      		found = chembl.searchTargets({filters = {target_components__accession = "P00533"}, fields = {"target_chembl_id"}})
      		assert(url() == API .. "/target.json?target_components__accession=P00533&only=target_chembl_id&limit=100&offset=0", url())
      		assert(found.targets[1].target_chembl_id == "CHEMBL203")
      		for _, case in {
      			{fn = chembl.searchAssays, path = "assay/search.json?q=EGFR%20kinase&", key = "assays",
      				args = {q = "EGFR kinase", fields = "all"}, size = 32},
      			{fn = chembl.searchDocuments, path = "document.json?pubmed_id=23028140&", key = "documents",
      				args = {filters = {pubmed_id = 23028140}, fields = "all"}, size = 32},
      			{fn = chembl.searchMechanisms, path = "mechanism.json?parent_molecule_chembl_id=CHEMBL941&", key = "mechanisms",
      				args = {filters = {parent_molecule_chembl_id = "CHEMBL941"}, fields = "all"}, size = 32},
      			{fn = chembl.searchDrugIndications, path = "drug_indication.json?efo_term__icontains=fibrillation&", key = "drug_indications",
      				args = {filters = {efo_term__icontains = "fibrillation"}, fields = {"drugind_id", "efo_term"}, limit = 50}, size = 50},
      		} do
      			respond(page(case.key, {"{}"}, 1, false))
      			local result = case.fn(case.args)
      			local only = if type(case.args.fields) == "table" then "only=drugind_id%2Cefo_term&" else ""
      			assert(url() == API .. "/" .. case.path .. only .. "limit=" .. case.size .. "&offset=0", url())
      			assert(#result[case.key] == 1 and result.total_count == 1)
      		end
      
      		-- Two pages: the second asks for the rest with less time, and an exactly full limit keeps next_offset.
      		respond(page("molecules", molecules(1, 1000), 4000, true))
      		respond(page("molecules", molecules(1001, 500), 9999, true))
      		local first = #requests + 1
      		found = chembl.searchMolecules({limit = 1500})
      		assert(url(first) == API .. "/molecule.json?" .. MOLECULE .. "&limit=1000&offset=0", url(first))
      		assert(url() == API .. "/molecule.json?" .. MOLECULE .. "&limit=500&offset=1000", url())
      		assert(requests[first].timeoutMs == 15000 and requests[first + 1].timeoutMs == 6000, "the second page gets what the call has left")
      		assert(#found.molecules == 1500 and found.molecules[1500].molecule_chembl_id == "CHEMBL1500")
      		assert(found.total_count == 4000 and found.next_offset == 1500, "total_count comes from the first page")
      
      		-- next_offset continues from the caller's offset; a page without a next link ends the search early.
      		respond(page("molecules", molecules(1, 1000), 1600, true))
      		respond(page("molecules", molecules(1001, 600), 1600, false))
      		found = chembl.searchMolecules({limit = 2000, offset = 0})
      		assert(#found.molecules == 1600 and found.next_offset == nil)
      		respond(page("molecules", molecules(1, 1000), 4000, true))
      		respond(page("molecules", molecules(1001, 1000), 4000, true))
      		found = chembl.searchMolecules({limit = 2000, offset = 2000})
      		assert(url() == API .. "/molecule.json?" .. MOLECULE .. "&limit=1000&offset=3000", url())
      		assert(#found.molecules == 2000 and found.next_offset == 4000)
      		found = nil
      
      		-- Records beyond the compact defaults start with 32 rows; the next page fits the remaining byte budget.
      		respond(page("molecules", molecules(1, 32, 100 * 1024), 500, true))
      		respond(page("molecules", molecules(33, 4), 500, true))
      		first = #requests + 1
      		found = chembl.searchMolecules({fields = "all", limit = 2000})
      		assert(url(first) == API .. "/molecule.json?limit=32&offset=0", url(first))
      		assert(url() == API .. "/molecule.json?limit=4&offset=32", url())
      		assert(#found.molecules == 36 and found.next_offset == 36)
      		found = nil
      
      		-- When nothing more fits, the call ends after one page.
      		respond(page("molecules", molecules(1, 32, 125 * 1024), 500, true))
      		first = #requests
      		found = chembl.searchMolecules({fields = {"molecule_structures"}, limit = 2000})
      		assert(#requests == first + 1, "the byte budget must stop paging")
      		assert(url() == API .. "/molecule.json?only=molecule_structures&limit=32&offset=0", url())
      		assert(#found.molecules == 32 and found.next_offset == 32)
      		found = nil
      
      		-- A second page over the remaining budget, or too slow, ends the call with what was collected.
      		respond(page("molecules", molecules(1, 1000, 1000), 4000, true))
      		respond(page("molecules", molecules(1001, 1, 3 * 1024 * 1024 + 100 * 1024), 4000, true))
      		found = chembl.searchMolecules({limit = 2000})
      		assert(#found.molecules == 1000 and found.next_offset == 1000, "collected molecules were discarded")
      		respond(page("molecules", molecules(1, 10), 4000, true))
      		respond({code = "timeout", message = "request deadline"})
      		found = chembl.searchMolecules({limit = 20, offset = 5})
      		assert(url() == API .. "/molecule.json?" .. MOLECULE .. "&limit=10&offset=15", url())
      		assert(#found.molecules == 10 and found.next_offset == 15)
      		-- Any other failure of a later page also keeps the collected rows; cancellation still ends the call.
      		for _, failed in {{status = 500, body = '{"error_message": "statement timeout"}'}, {status = 404}, {code = "io_error", message = "reset"},
      			{readError = {code = "timeout", message = "await timed out"}},
      			{readError = {code = "io_error", message = "reset"}}, '<html>', '{"molecules": null}'} do
      			respond(page("molecules", molecules(1, 10), 4000, true))
      			respond(failed)
      			found = chembl.searchMolecules({limit = 20})
      			assert(#found.molecules == 10 and found.next_offset == 10, "a later page failure discarded the collected rows")
      		end
      		respond(page("molecules", molecules(1, 10), 4000, true))
      		respond({readError = {code = "cancelled", message = "invocation cancelled"}})
      		local cancelled, err = pcall(chembl.searchMolecules, {limit = 20})
      		assert(not cancelled and not string.find(tostring(err), "retryable", 1, true), "cancellation became a result: " .. tostring(err))
      		found = nil
      
      		-- Structure searches use the query-string form, so SMILES characters such as # and / are encoded.
      		local SIMILAR = MOLECULE .. "%2Csimilarity"
      		respond(page("molecules", {'{"molecule_chembl_id":"CHEMBL25","similarity":"100"}'}, 1, false))
      		found = chembl.similarMolecules({smiles = "CC(=O)Oc1ccccc1C(=O)O"})
      		assert(url() == API .. "/similarity.json?similarity=80&smiles=CC%28%3DO%29Oc1ccccc1C%28%3DO%29O&" .. SIMILAR
      			.. "&limit=100&offset=0", url())
      		assert(found.molecules[1].similarity == "100")
      		respond(page("molecules", {}, 0, false))
      		found = chembl.similarMolecules({chembl_id = "chembl25", similarity = 40, filters = {max_phase = 4},
      			order_by = "-similarity", limit = 10})
      		assert(url() == API .. "/similarity.json?chembl_id=CHEMBL25&max_phase=4&similarity=40&order_by=-similarity&"
      			.. SIMILAR .. "&limit=10&offset=0", url())
      		assert(json.encode(found.molecules) == "[]" and found.next_offset == nil)
      		respond(page("molecules", molecules(1, 3), 30000, true))
      		found = chembl.substructureMolecules({smiles = "C#CC/C=C\\c1ccccc1", limit = 3})
      		assert(url() == API .. "/substructure.json?smiles=C%23CC%2FC%3DC%5Cc1ccccc1&" .. MOLECULE .. "&limit=3&offset=0", url())
      		assert(#found.molecules == 3 and found.total_count == 30000 and found.next_offset == 3)
      		respond(page("molecules", {}, 0, false))
      		chembl.substructureMolecules({chembl_id = "CHEMBL25", fields = "all"})
      		assert(url() == API .. "/substructure.json?chembl_id=CHEMBL25&limit=32&offset=0", url())
      
      		-- Records by ID: ChEMBL IDs are upper-cased, InChIKeys and integer IDs pass as they are.
      		for _, case in {
      			{fn = chembl.getMolecule, id = "chembl25", path = "molecule/CHEMBL25.json"},
      			{fn = chembl.getMolecule, id = "BSYNRYMUTXBXSQ-UHFFFAOYSA-N", path = "molecule/BSYNRYMUTXBXSQ-UHFFFAOYSA-N.json"},
      			{fn = chembl.getTarget, id = "CHEMBL203", path = "target/CHEMBL203.json"},
      			{fn = chembl.getAssay, id = "CHEMBL1217643", path = "assay/CHEMBL1217643.json"},
      			{fn = chembl.getDocument, id = "CHEMBL1139451", path = "document/CHEMBL1139451.json"},
      			{fn = chembl.getActivity, id = 31863, path = "activity/31863.json"},
      			{fn = chembl.getMechanism, id = "241", path = "mechanism/241.json"},
      			{fn = chembl.getDrugIndication, id = 22713, path = "drug_indication/22713.json"},
      		} do
      			respond('{"id":"record"}')
      			assert(case.fn(case.id).id == "record")
      			assert(url() == API .. "/" .. case.path, url())
      			assert(requests[#requests].timeoutMs == 24000)
      		end
      		respond('{"target_chembl_id":"CHEMBL203","target_components":[]}')
      		local target = chembl.getTarget("CHEMBL203", {fields = {"target_chembl_id", "target_components"}})
      		assert(url() == API .. "/target/CHEMBL203.json?only=target_chembl_id%2Ctarget_components", url())
      		assert(json.encode(target.target_components) == "[]")
      		respond('{"molecule_chembl_id":"CHEMBL25"}')
      		chembl.getMolecule("CHEMBL25", {fields = "all"})
      		assert(url() == API .. "/molecule/CHEMBL25.json", url())
      		assert(#responses == 0, "unused responses")
      	end,
      }