[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ED06YSP55NKG57MMXQKX8T":3,"skill-same:01M7ED06YSP55NKG57MMXQKX8T":70},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M7ED06YSP55NKG57MMXQKX8T","bio-entrez-fetch",null,"Retrieve records from NCBI databases using Biopython Bio.Entrez (EFetch, ESummary). Use when downloading sequences, fetching GenBank\u002FGenPept records, getting document summaries, parsing nested XML, navigating GI deprecation, choosing between rettype+retmode combinations, and parsing into Biopython SeqRecord\u002FSwissProt objects. Covers nucleotide, protein, gene, pubmed, sra, gds, taxonomy, snp, clinvar.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-entrez-fetch\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-entrez-fetch\ndescription: Retrieve records from NCBI databases using Biopython Bio.Entrez (EFetch, ESummary). Use when downloading sequences, fetching GenBank\u002FGenPept records, getting document summaries, parsing nested XML, navigating GI deprecation, choosing between rettype+retmode combinations, and parsing into Biopython SeqRecord\u002FSwissProt objects. Covers nucleotide, protein, gene, pubmed, sra, gds, taxonomy, snp, clinvar.\ntool_type: python\nprimary_tool: Bio.Entrez\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"database-access\u002Fentrez-fetch\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: BioPython 1.83+, Entrez Direct 21.0+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show biopython` then `help(Bio.Entrez.efetch)` to check signatures\n- CLI: `efetch -version` then `efetch -help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Entrez Fetch\n\n**\"Download a record by accession from NCBI\"** -> EFetch returns the full record content in a chosen format (FASTA, GenBank, XML, MEDLINE, etc.). ESummary returns a lightweight \"docsum\" object — much faster when only metadata is needed.\n\nThe agent's first decision is always: does this workflow need the full record, or just metadata? ESummary is 5-10x cheaper than EFetch for the equivalent record set. For \"tell me the organism, length, and definition line for 10,000 accessions\", ESummary wins by an order of magnitude.\n\n- Python: `Entrez.efetch(db=..., id=..., rettype=..., retmode=...)` (BioPython)\n- CLI: `efetch -db nucleotide -id NM_007294 -format gb` (Entrez Direct, NBK179288)\n- R: `entrez_fetch(db=..., id=..., rettype=...)` (rentrez)\n\n## Required Setup\n\n```python\nfrom Bio import Entrez, SeqIO\nEntrez.email = 'researcher@institution.edu'\nEntrez.api_key = 'optional_api_key'  # raises rate to 10 req\u002Fsec\n```\n\n## Decision matrix: rettype + retmode per database\n\nThe combinations are not orthogonal — each (db, rettype, retmode) triple is enabled or disabled by NCBI server-side. Wrong combinations return either silent empty responses or HTTP 400. The triples below are the safe, current set.\n\n### nucleotide \u002F protein\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| `fasta` | `text` | FASTA | Just need sequence + defline |\n| `gb` (nuc) \u002F `gp` (prot) | `text` | Full flat file | Need annotations, features, references |\n| `gbwithparts` | `text` | GB with CONTIG sequences inlined | Whole-genome shotgun assemblies; default `gb` returns CONTIG records requiring a chase to resolve |\n| `fasta_cds_na` | `text` | CDS-only nucleotide | Extract coding regions from annotated GB |\n| `fasta_cds_aa` | `text` | CDS-translated AA | Get translated proteins from GB record in one call |\n| `xml` (== gb XML) | `xml` | INSDSeq XML | Programmatic parsing; the schema is unversioned and shifts |\n| `acc` | `text` | Accession.version per line | Just resolve UID -> accession |\n| `seqid` | `text` | Internal seq-id | Rarely needed |\n\n### pubmed\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| `abstract` | `text` | Title + authors + abstract | Reading abstracts |\n| `medline` | `text` | MEDLINE flat | Parsing with `Bio.Medline` |\n| `xml` | `xml` | Full PubMed XML | Programmatic — get MeSH, grants, PMC link |\n| (omitted) | (omitted) | Defaults to XML | EFetch default for pubmed is XML — pass `retmode='xml'` explicitly for clarity |\n\n### gene\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| `gene_table` | `text` | Tabular per-transcript layout | Exon coordinates |\n| `xml` | `xml` | Full Entrez Gene XML | Everything else — name, synonyms, GeneRIFs, locus |\n\n### sra\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| `runinfo` | `text` | CSV of run metadata | Convert SRA UID -> SRR accession + Run metrics |\n| `xml` | `xml` | Full SRA XML hierarchy | Need BioSample\u002FBioProject linkage in one call |\n\n### taxonomy\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| `xml` | `xml` (default) | TaxNode XML | Lineage, parent, common name |\n\n### gds (GEO)\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| (default — no rettype) | `text` | Plaintext SOFT-style summary | Quick metadata; for full series matrix go to FTP |\n\nEFetch for GDS records is intentionally minimal — full GEO downloads go via the FTP mirror or `GEOparse`. See `geo-data` skill.\n\n## GI deprecation (still bites in 2026)\n\nNCBI stopped issuing new GI numbers for major nucleotide\u002Fprotein submissions starting 2017. Records submitted after the cutoff have only `accession.version` identifiers. Many older scripts assume `id=\u003Cnumeric_gi>`; passing a modern accession string also works, but mixing the two in one comma-separated id list is the bug.\n\n**Rules:**\n- For modern code, always pass `accession.version` strings.\n- A bare accession without `.version` resolves to the latest version — fine for exploratory work, dangerous for reproducibility.\n- Old `id=12345` GI lookups still work for records issued before 2017, but a search returning a UID that looks like a GI may actually be the legacy GI for an old record — assume UID is an opaque identifier.\n- EFetch accepts comma-separated IDs of mixed types but the URL has a ~2000 char practical limit; chunk large ID lists into batches.\n\n## ESummary vs EFetch triage\n\n| Need | ESummary | EFetch (text) | EFetch (xml) |\n|---|---|---|---|\n| Title, organism, length | yes | overkill | overkill |\n| Authors of a PubMed article | yes | yes | yes |\n| Full abstract text | no | `rettype=abstract` | better — structured |\n| MeSH terms, grant info, PMC ID | no | no | yes |\n| Sequence | no | `rettype=fasta` | overkill |\n| Sequence features (CDS, exons) | no | `rettype=gb` | yes |\n| Cross-references (xref) | partial | yes (in GB) | yes |\n| Bulk metadata for 10K records | best (1 call per ~500) | slow | slow |\n\nESummary's documented hard limit is 10,000 docsums per call, but the practical sweet spot is ~500 (keeps the URL under length limits when IDs are comma-joined; for >500 use EPost to push IDs server-side first). Per-record payload is much smaller than EFetch. Use ESummary as the default for any metadata-only workflow.\n\n## XML schema brittleness\n\n`Entrez.read()` parses INSDSeq XML, PubmedArticle XML, Gene XML, etc. The schemas are NOT versioned; NCBI adds and renames fields without notice. Real-world consequence: a parser that worked in 2022 may KeyError in 2026 because a nested field moved.\n\nDefensive patterns:\n- Use `.get(key, default)` not `[key]` for every nested field\n- For sequence content, prefer `SeqIO.read()` over `Entrez.read()` — the SeqIO parsers are versioned with BioPython\n- Pin BioPython version in production code; expect to update the parser when NCBI changes the XML\n- For PubMed, `Bio.Medline.parse(handle)` (against `rettype='medline'`) is more stable than the XML route\n\n## Code patterns\n\n### Single sequence by accession\n\n**Goal:** Fetch one nucleotide record as a SeqRecord with features.\n\n**Approach:** EFetch with `rettype='gb', retmode='text'`; parse with `SeqIO.read()`.\n\n**Reference (BioPython 1.83+):**\n```python\ndef fetch_genbank(accession):\n    h = Entrez.efetch(db='nucleotide', id=accession, rettype='gb', retmode='text')\n    record = SeqIO.read(h, 'genbank'); h.close()\n    return record\n\ngb = fetch_genbank('NM_007294.4')\nfor feat in gb.features:\n    if feat.type == 'CDS':\n        print(feat.location, feat.qualifiers.get('product', ['?'])[0])\n```\n\n### Bulk metadata via ESummary\n\n**Goal:** Get organism + length + title for 1,000 UIDs without downloading sequences.\n\n**Approach:** ESummary on a comma-joined ID batch (max 500 per call by convention; supports 10K hard limit).\n\n**Reference (BioPython 1.83+):**\n```python\ndef bulk_summaries(db, ids, chunk=500):\n    out = []\n    for i in range(0, len(ids), chunk):\n        h = Entrez.esummary(db=db, id=','.join(ids[i:i+chunk]))\n        out.extend(Entrez.read(h)); h.close()\n        time.sleep(0.1 if Entrez.api_key else 0.34)\n    return out\n\nrecords = bulk_summaries('nucleotide', uid_list)\n```\n\n### Extract CDS in one round-trip\n\n**Goal:** Download the CDS-only translated protein sequences from a GenBank record without manually walking features.\n\n**Approach:** Use `rettype='fasta_cds_aa'` — NCBI server-side extracts and translates every CDS in the record.\n\n**Reference (BioPython 1.83+):**\n```python\ndef cds_proteins(accession):\n    h = Entrez.efetch(db='nucleotide', id=accession, rettype='fasta_cds_aa', retmode='text')\n    return list(SeqIO.parse(h, 'fasta'))\n\nproteins = cds_proteins('NC_000913.3')  # E. coli K-12 genome\nprint(f'{len(proteins)} CDS-translated proteins')\n```\n\n### Pull PubMed with structured MeSH\n\n**Goal:** Get MeSH terms and grant information that aren't in the abstract format.\n\n**Approach:** `rettype='xml'` and walk the PubmedArticle structure defensively.\n\n**Reference (BioPython 1.83+):**\n```python\ndef pubmed_full(pmid):\n    h = Entrez.efetch(db='pubmed', id=pmid, retmode='xml')\n    records = Entrez.read(h); h.close()\n    article = records['PubmedArticle'][0]\n    citation = article['MedlineCitation']\n    mesh = [m['DescriptorName'] for m in citation.get('MeshHeadingList', [])]\n    title = citation['Article']['ArticleTitle']\n    return {'pmid': pmid, 'title': title, 'mesh': mesh}\n```\n\n### History-server fetch (post-ESearch)\n\n**Goal:** Pull a 50,000-record result set without re-sending UIDs.\n\n**Approach:** ESearch with `usehistory='y'`; iterate EFetch with `webenv`\u002F`query_key` and `retstart`. See `batch-downloads` for the production pattern.\n\n```python\nh = Entrez.esearch(db='nucleotide', term='Homo sapiens[ORGN] AND srcdb_refseq[PROP] AND biomol_mrna[PROP]',\n                   usehistory='y', retmax=0)\nr = Entrez.read(h); h.close()\ntotal = int(r['Count'])\n\nwith open('out.fasta', 'w') as out:\n    for start in range(0, total, 500):\n        h = Entrez.efetch(db='nucleotide', rettype='fasta', retmode='text',\n                          retstart=start, retmax=500,\n                          webenv=r['WebEnv'], query_key=r['QueryKey'])\n        out.write(h.read()); h.close()\n        time.sleep(0.1 if Entrez.api_key else 0.34)\n```\n\n### SRA UID -> SRR accession + run metrics\n\n**Goal:** Convert an opaque SRA UID into the SRR run accession plus Bases\u002FSpots metrics, in one EFetch.\n\n**Approach:** `rettype='runinfo'` returns a CSV row per run.\n\n```python\ndef sra_runinfo(uids):\n    h = Entrez.efetch(db='sra', id=','.join(uids), rettype='runinfo', retmode='text')\n    text = h.read(); h.close()\n    lines = text.strip().split('\\n')\n    header = lines[0].split(',')\n    return [dict(zip(header, row.split(','))) for row in lines[1:]]\n```\n\n### Taxonomy lineage by TXID\n\n```python\ndef lineage(txid):\n    h = Entrez.efetch(db='taxonomy', id=str(txid), retmode='xml')\n    record = Entrez.read(h)[0]; h.close()\n    return record['Lineage'], record['ScientificName']\n```\n\n## Failure modes\n\n### Mixed-format batch silently truncates\n- **Trigger:** Mixing modern accessions and legacy GIs in one comma-separated `id=`.\n- **Mechanism:** EFetch parses left-to-right; on type-mismatch it may return only the prefix that succeeded.\n- **Symptom:** Batch of 100 returns 47 records with no error.\n- **Fix:** Validate that all IDs in a batch are the same type before sending.\n\n### `gb` returns CONTIG instead of sequence\n- **Trigger:** Fetching a whole-genome shotgun (WGS) assembly with `rettype='gb'`.\n- **Mechanism:** Default GB output skips the contig sequence for assemblies, returning only the join() statement.\n- **Symptom:** `len(record.seq) == 0` despite the record showing a length in metadata.\n- **Fix:** Use `rettype='gbwithparts'` for assemblies; or for FASTA use `rettype='fasta'` directly.\n\n### XML parse fails on schema drift\n- **Trigger:** Code that was last touched in 2022 hits a new NCBI XML field layout.\n- **Mechanism:** `Entrez.read()` uses cached DTDs that may not match current responses.\n- **Symptom:** KeyError or ValidationError on a field that \"always worked\".\n- **Fix:** Run `Entrez.read._XMLParser._DTDs.clear()` to force re-fetch of DTDs; upgrade BioPython; or switch to text format (`rettype='medline'` for pubmed) which is more stable.\n\n### Silent empty response on bad rettype\n- **Trigger:** Asking for `rettype='abstract'` on the nucleotide db (only valid for pubmed).\n- **Mechanism:** EFetch returns empty text — no HTTP error.\n- **Symptom:** `handle.read()` returns `''` or whitespace.\n- **Fix:** Check the decision matrix above before sending unfamiliar combinations.\n\n### Accession without `.version` returns wrong record later\n- **Trigger:** Storing `'NM_007294'` (no version) for reproducibility years later.\n- **Mechanism:** NCBI returns the current version, which may have changed annotation.\n- **Symptom:** Re-run produces different CDS coordinates than the original analysis.\n- **Fix:** Always pin `accession.version` (e.g. `NM_007294.4`); the version is in the GB LOCUS line.\n\n### EFetch returns HTML error page\n- **Trigger:** Invalid UID, mid-maintenance window, or expired WebEnv.\n- **Mechanism:** Failure surfaces in HTML body, HTTP status is 200.\n- **Symptom:** SeqIO chokes parsing HTML as GenBank.\n- **Fix:** Sniff the first line of the response — `LOCUS` for GB, `>` for FASTA — and raise on mismatch.\n\n## Common errors\n\n| Error \u002F symptom | Cause | Solution |\n|---|---|---|\n| `HTTPError 400` | Invalid id\u002Fdb\u002Frettype combo | Verify against decision matrix; check accession exists |\n| `HTTPError 429` | Rate limit exceeded | Add `time.sleep(0.34)` or use API key |\n| Empty `SeqRecord.seq` | WGS record with `rettype='gb'` | Use `rettype='gbwithparts'` |\n| `ValueError: Sequence too short` | Wrong format declared to SeqIO | Match rettype to `SeqIO` format string |\n| `ExpatError` | Got HTML where XML expected | Sniff response start; retry |\n| KeyError on nested XML field | Schema drift | Use `.get()` defensively; pin BioPython |\n\n## References\n\n- Sayers EW et al. (2024) Database resources of the National Center for Biotechnology Information in 2024. *Nucleic Acids Res* 52:D33-D43.\n- Kans J. (2024) Entrez Direct: E-utilities on the Unix Command Line. NCBI Bookshelf NBK179288.\n- NCBI. EFetch help. NBK25499.\n- Cock PJ et al. (2009) Biopython: freely available Python tools for computational molecular biology and bioinformatics. *Bioinformatics* 25:1422-1423.\n\n## Related Skills\n\n- entrez-search - Find UIDs before fetching\n- entrez-link - Cross-database navigation via ELink\n- batch-downloads - History-server pipelines for large fetches\n- ncbi-datasets-cli - Modern CLI for genome \u002F gene metadata; often faster than EFetch\n- sequence-io\u002Fread-sequences - Parse downloaded FASTA\u002FGenBank with SeqIO\n","## Version Compatibility\n\nReference examples tested with: BioPython 1.83+, Entrez Direct 21.0+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show biopython` then `help(Bio.Entrez.efetch)` to check signatures\n- CLI: `efetch -version` then `efetch -help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Entrez Fetch\n\n**\"Download a record by accession from NCBI\"** -> EFetch returns the full record content in a chosen format (FASTA, GenBank, XML, MEDLINE, etc.). ESummary returns a lightweight \"docsum\" object — much faster when only metadata is needed.\n\nThe agent's first decision is always: does this workflow need the full record, or just metadata? ESummary is 5-10x cheaper than EFetch for the equivalent record set. For \"tell me the organism, length, and definition line for 10,000 accessions\", ESummary wins by an order of magnitude.\n\n- Python: `Entrez.efetch(db=..., id=..., rettype=..., retmode=...)` (BioPython)\n- CLI: `efetch -db nucleotide -id NM_007294 -format gb` (Entrez Direct, NBK179288)\n- R: `entrez_fetch(db=..., id=..., rettype=...)` (rentrez)\n\n## Required Setup\n\n```python\nfrom Bio import Entrez, SeqIO\nEntrez.email = 'researcher@institution.edu'\nEntrez.api_key = 'optional_api_key'  # raises rate to 10 req\u002Fsec\n```\n\n## Decision matrix: rettype + retmode per database\n\nThe combinations are not orthogonal — each (db, rettype, retmode) triple is enabled or disabled by NCBI server-side. Wrong combinations return either silent empty responses or HTTP 400. The triples below are the safe, current set.\n\n### nucleotide \u002F protein\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| `fasta` | `text` | FASTA | Just need sequence + defline |\n| `gb` (nuc) \u002F `gp` (prot) | `text` | Full flat file | Need annotations, features, references |\n| `gbwithparts` | `text` | GB with CONTIG sequences inlined | Whole-genome shotgun assemblies; default `gb` returns CONTIG records requiring a chase to resolve |\n| `fasta_cds_na` | `text` | CDS-only nucleotide | Extract coding regions from annotated GB |\n| `fasta_cds_aa` | `text` | CDS-translated AA | Get translated proteins from GB record in one call |\n| `xml` (== gb XML) | `xml` | INSDSeq XML | Programmatic parsing; the schema is unversioned and shifts |\n| `acc` | `text` | Accession.version per line | Just resolve UID -> accession |\n| `seqid` | `text` | Internal seq-id | Rarely needed |\n\n### pubmed\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| `abstract` | `text` | Title + authors + abstract | Reading abstracts |\n| `medline` | `text` | MEDLINE flat | Parsing with `Bio.Medline` |\n| `xml` | `xml` | Full PubMed XML | Programmatic — get MeSH, grants, PMC link |\n| (omitted) | (omitted) | Defaults to XML | EFetch default for pubmed is XML — pass `retmode='xml'` explicitly for clarity |\n\n### gene\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| `gene_table` | `text` | Tabular per-transcript layout | Exon coordinates |\n| `xml` | `xml` | Full Entrez Gene XML | Everything else — name, synonyms, GeneRIFs, locus |\n\n### sra\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| `runinfo` | `text` | CSV of run metadata | Convert SRA UID -> SRR accession + Run metrics |\n| `xml` | `xml` | Full SRA XML hierarchy | Need BioSample\u002FBioProject linkage in one call |\n\n### taxonomy\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| `xml` | `xml` (default) | TaxNode XML | Lineage, parent, common name |\n\n### gds (GEO)\n\n| rettype | retmode | Returns | Use when |\n|---|---|---|---|\n| (default — no rettype) | `text` | Plaintext SOFT-style summary | Quick metadata; for full series matrix go to FTP |\n\nEFetch for GDS records is intentionally minimal — full GEO downloads go via the FTP mirror or `GEOparse`. See `geo-data` skill.\n\n## GI deprecation (still bites in 2026)\n\nNCBI stopped issuing new GI numbers for major nucleotide\u002Fprotein submissions starting 2017. Records submitted after the cutoff have only `accession.version` identifiers. Many older scripts assume `id=\u003Cnumeric_gi>`; passing a modern accession string also works, but mixing the two in one comma-separated id list is the bug.\n\n**Rules:**\n- For modern code, always pass `accession.version` strings.\n- A bare accession without `.version` resolves to the latest version — fine for exploratory work, dangerous for reproducibility.\n- Old `id=12345` GI lookups still work for records issued before 2017, but a search returning a UID that looks like a GI may actually be the legacy GI for an old record — assume UID is an opaque identifier.\n- EFetch accepts comma-separated IDs of mixed types but the URL has a ~2000 char practical limit; chunk large ID lists into batches.\n\n## ESummary vs EFetch triage\n\n| Need | ESummary | EFetch (text) | EFetch (xml) |\n|---|---|---|---|\n| Title, organism, length | yes | overkill | overkill |\n| Authors of a PubMed article | yes | yes | yes |\n| Full abstract text | no | `rettype=abstract` | better — structured |\n| MeSH terms, grant info, PMC ID | no | no | yes |\n| Sequence | no | `rettype=fasta` | overkill |\n| Sequence features (CDS, exons) | no | `rettype=gb` | yes |\n| Cross-references (xref) | partial | yes (in GB) | yes |\n| Bulk metadata for 10K records | best (1 call per ~500) | slow | slow |\n\nESummary's documented hard limit is 10,000 docsums per call, but the practical sweet spot is ~500 (keeps the URL under length limits when IDs are comma-joined; for >500 use EPost to push IDs server-side first). Per-record payload is much smaller than EFetch. Use ESummary as the default for any metadata-only workflow.\n\n## XML schema brittleness\n\n`Entrez.read()` parses INSDSeq XML, PubmedArticle XML, Gene XML, etc. The schemas are NOT versioned; NCBI adds and renames fields without notice. Real-world consequence: a parser that worked in 2022 may KeyError in 2026 because a nested field moved.\n\nDefensive patterns:\n- Use `.get(key, default)` not `[key]` for every nested field\n- For sequence content, prefer `SeqIO.read()` over `Entrez.read()` — the SeqIO parsers are versioned with BioPython\n- Pin BioPython version in production code; expect to update the parser when NCBI changes the XML\n- For PubMed, `Bio.Medline.parse(handle)` (against `rettype='medline'`) is more stable than the XML route\n\n## Code patterns\n\n### Single sequence by accession\n\n**Goal:** Fetch one nucleotide record as a SeqRecord with features.\n\n**Approach:** EFetch with `rettype='gb', retmode='text'`; parse with `SeqIO.read()`.\n\n**Reference (BioPython 1.83+):**\n```python\ndef fetch_genbank(accession):\n    h = Entrez.efetch(db='nucleotide', id=accession, rettype='gb', retmode='text')\n    record = SeqIO.read(h, 'genbank'); h.close()\n    return record\n\ngb = fetch_genbank('NM_007294.4')\nfor feat in gb.features:\n    if feat.type == 'CDS':\n        print(feat.location, feat.qualifiers.get('product', ['?'])[0])\n```\n\n### Bulk metadata via ESummary\n\n**Goal:** Get organism + length + title for 1,000 UIDs without downloading sequences.\n\n**Approach:** ESummary on a comma-joined ID batch (max 500 per call by convention; supports 10K hard limit).\n\n**Reference (BioPython 1.83+):**\n```python\ndef bulk_summaries(db, ids, chunk=500):\n    out = []\n    for i in range(0, len(ids), chunk):\n        h = Entrez.esummary(db=db, id=','.join(ids[i:i+chunk]))\n        out.extend(Entrez.read(h)); h.close()\n        time.sleep(0.1 if Entrez.api_key else 0.34)\n    return out\n\nrecords = bulk_summaries('nucleotide', uid_list)\n```\n\n### Extract CDS in one round-trip\n\n**Goal:** Download the CDS-only translated protein sequences from a GenBank record without manually walking features.\n\n**Approach:** Use `rettype='fasta_cds_aa'` — NCBI server-side extracts and translates every CDS in the record.\n\n**Reference (BioPython 1.83+):**\n```python\ndef cds_proteins(accession):\n    h = Entrez.efetch(db='nucleotide', id=accession, rettype='fasta_cds_aa', retmode='text')\n    return list(SeqIO.parse(h, 'fasta'))\n\nproteins = cds_proteins('NC_000913.3')  # E. coli K-12 genome\nprint(f'{len(proteins)} CDS-translated proteins')\n```\n\n### Pull PubMed with structured MeSH\n\n**Goal:** Get MeSH terms and grant information that aren't in the abstract format.\n\n**Approach:** `rettype='xml'` and walk the PubmedArticle structure defensively.\n\n**Reference (BioPython 1.83+):**\n```python\ndef pubmed_full(pmid):\n    h = Entrez.efetch(db='pubmed', id=pmid, retmode='xml')\n    records = Entrez.read(h); h.close()\n    article = records['PubmedArticle'][0]\n    citation = article['MedlineCitation']\n    mesh = [m['DescriptorName'] for m in citation.get('MeshHeadingList', [])]\n    title = citation['Article']['ArticleTitle']\n    return {'pmid': pmid, 'title': title, 'mesh': mesh}\n```\n\n### History-server fetch (post-ESearch)\n\n**Goal:** Pull a 50,000-record result set without re-sending UIDs.\n\n**Approach:** ESearch with `usehistory='y'`; iterate EFetch with `webenv`\u002F`query_key` and `retstart`. See `batch-downloads` for the production pattern.\n\n```python\nh = Entrez.esearch(db='nucleotide', term='Homo sapiens[ORGN] AND srcdb_refseq[PROP] AND biomol_mrna[PROP]',\n                   usehistory='y', retmax=0)\nr = Entrez.read(h); h.close()\ntotal = int(r['Count'])\n\nwith open('out.fasta', 'w') as out:\n    for start in range(0, total, 500):\n        h = Entrez.efetch(db='nucleotide', rettype='fasta', retmode='text',\n                          retstart=start, retmax=500,\n                          webenv=r['WebEnv'], query_key=r['QueryKey'])\n        out.write(h.read()); h.close()\n        time.sleep(0.1 if Entrez.api_key else 0.34)\n```\n\n### SRA UID -> SRR accession + run metrics\n\n**Goal:** Convert an opaque SRA UID into the SRR run accession plus Bases\u002FSpots metrics, in one EFetch.\n\n**Approach:** `rettype='runinfo'` returns a CSV row per run.\n\n```python\ndef sra_runinfo(uids):\n    h = Entrez.efetch(db='sra', id=','.join(uids), rettype='runinfo', retmode='text')\n    text = h.read(); h.close()\n    lines = text.strip().split('\\n')\n    header = lines[0].split(',')\n    return [dict(zip(header, row.split(','))) for row in lines[1:]]\n```\n\n### Taxonomy lineage by TXID\n\n```python\ndef lineage(txid):\n    h = Entrez.efetch(db='taxonomy', id=str(txid), retmode='xml')\n    record = Entrez.read(h)[0]; h.close()\n    return record['Lineage'], record['ScientificName']\n```\n\n## Failure modes\n\n### Mixed-format batch silently truncates\n- **Trigger:** Mixing modern accessions and legacy GIs in one comma-separated `id=`.\n- **Mechanism:** EFetch parses left-to-right; on type-mismatch it may return only the prefix that succeeded.\n- **Symptom:** Batch of 100 returns 47 records with no error.\n- **Fix:** Validate that all IDs in a batch are the same type before sending.\n\n### `gb` returns CONTIG instead of sequence\n- **Trigger:** Fetching a whole-genome shotgun (WGS) assembly with `rettype='gb'`.\n- **Mechanism:** Default GB output skips the contig sequence for assemblies, returning only the join() statement.\n- **Symptom:** `len(record.seq) == 0` despite the record showing a length in metadata.\n- **Fix:** Use `rettype='gbwithparts'` for assemblies; or for FASTA use `rettype='fasta'` directly.\n\n### XML parse fails on schema drift\n- **Trigger:** Code that was last touched in 2022 hits a new NCBI XML field layout.\n- **Mechanism:** `Entrez.read()` uses cached DTDs that may not match current responses.\n- **Symptom:** KeyError or ValidationError on a field that \"always worked\".\n- **Fix:** Run `Entrez.read._XMLParser._DTDs.clear()` to force re-fetch of DTDs; upgrade BioPython; or switch to text format (`rettype='medline'` for pubmed) which is more stable.\n\n### Silent empty response on bad rettype\n- **Trigger:** Asking for `rettype='abstract'` on the nucleotide db (only valid for pubmed).\n- **Mechanism:** EFetch returns empty text — no HTTP error.\n- **Symptom:** `handle.read()` returns `''` or whitespace.\n- **Fix:** Check the decision matrix above before sending unfamiliar combinations.\n\n### Accession without `.version` returns wrong record later\n- **Trigger:** Storing `'NM_007294'` (no version) for reproducibility years later.\n- **Mechanism:** NCBI returns the current version, which may have changed annotation.\n- **Symptom:** Re-run produces different CDS coordinates than the original analysis.\n- **Fix:** Always pin `accession.version` (e.g. `NM_007294.4`); the version is in the GB LOCUS line.\n\n### EFetch returns HTML error page\n- **Trigger:** Invalid UID, mid-maintenance window, or expired WebEnv.\n- **Mechanism:** Failure surfaces in HTML body, HTTP status is 200.\n- **Symptom:** SeqIO chokes parsing HTML as GenBank.\n- **Fix:** Sniff the first line of the response — `LOCUS` for GB, `>` for FASTA — and raise on mismatch.\n\n## Common errors\n\n| Error \u002F symptom | Cause | Solution |\n|---|---|---|\n| `HTTPError 400` | Invalid id\u002Fdb\u002Frettype combo | Verify against decision matrix; check accession exists |\n| `HTTPError 429` | Rate limit exceeded | Add `time.sleep(0.34)` or use API key |\n| Empty `SeqRecord.seq` | WGS record with `rettype='gb'` | Use `rettype='gbwithparts'` |\n| `ValueError: Sequence too short` | Wrong format declared to SeqIO | Match rettype to `SeqIO` format string |\n| `ExpatError` | Got HTML where XML expected | Sniff response start; retry |\n| KeyError on nested XML field | Schema drift | Use `.get()` defensively; pin BioPython |\n\n## References\n\n- Sayers EW et al. (2024) Database resources of the National Center for Biotechnology Information in 2024. *Nucleic Acids Res* 52:D33-D43.\n- Kans J. (2024) Entrez Direct: E-utilities on the Unix Command Line. NCBI Bookshelf NBK179288.\n- NCBI. EFetch help. NBK25499.\n- Cock PJ et al. (2009) Biopython: freely available Python tools for computational molecular biology and bioinformatics. *Bioinformatics* 25:1422-1423.\n\n## Related Skills\n\n- entrez-search - Find UIDs before fetching\n- entrez-link - Cross-database navigation via ELink\n- batch-downloads - History-server pipelines for large fetches\n- ncbi-datasets-cli - Modern CLI for genome \u002F gene metadata; often faster than EFetch\n- sequence-io\u002Fread-sequences - Parse downloaded FASTA\u002FGenBank with SeqIO\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","python","2026-09-20","database-access\u002Fentrez-fetch\u002FSKILL.md","Bio.Entrez","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-entrez-fetch","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-entrez-fetch",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-entrez-fetch",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-entrez-fetch","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-entrez-fetch\u002FSKILL.md",true,[50,56,60,64],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Ffetch_pubmed.py","SCRIPT","脚本",2210,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-entrez-fetch\u002Fexamples\u002Ffetch_pubmed.py",{"path":57,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":58,"sourceHtmlUrl":59},"examples\u002Ffetch_sequences.py",2267,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-entrez-fetch\u002Fexamples\u002Ffetch_sequences.py",{"path":61,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":62,"sourceHtmlUrl":63},"examples\u002Ffetch_summaries.py",1881,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-entrez-fetch\u002Fexamples\u002Ffetch_summaries.py",{"path":65,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":68,"sourceHtmlUrl":69},"usage-guide.md","REFERENCE","参考文档",4355,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-entrez-fetch\u002Fusage-guide.md",[71,79,86,93,100,107],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":78},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":78},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":78},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":78},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":78},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":78},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]