Entrez Database (NCBI)
Bio.Entrez is Biopython's interface to NCBI Entrez: a unified API across GenBank, PubMed, Protein, Nucleotide, and related databases. You build queries, run searches, and fetch records or files - all with polite, rate-limited HTTP calls that respect NCBI's terms (an API key and your email are strongly recommended).
Setup: Email and API Key
from Bio import Entrez
Entrez.email = "[email protected]" # NCBI asks for contact info
Entrez.api_key = "your_ncbi_api_key" # raises your rate limit (free at ncbi.nlm.nih.gov/account)
esearch: Find Accession Numbers
from Bio import Entrez
handle = Entrez.esearch(
db="nucleotide",
term="Haemophilus influenzae genome",
retmax=5,
)
results = Entrez.read(handle)
handle.close()
print(results["IdList"]) # list of accessions, e.g. ['NC_000913.3', ...]
efetch: Download the Records
from Bio import Entrez, SeqIO
handle = Entrez.efetch(
db="nucleotide",
id=["NC_000913.3"],
rettype="gb",
retmode="text",
)
records = list(SeqIO.parse(handle, "genbank"))
handle.close()
rec = records[0]
print(rec.id, len(rec), "bp")
print(rec.annotations.get("source"))
PubMed Example
from Bio import Entrez
handle = Entrez.esearch(db="pubmed", term="biopython AND tutorial", retmax=3)
res = Entrez.read(handle)
handle.close()
handle = Entrez.efetch(db="pubmed", id=res["IdList"], retmode="xml")
from xml.etree import ElementTree
root = ElementTree.parse(handle)
handle.close()
for article in root.iter("PubmedArticle"):
title = article.find(".//ArticleTitle")
pmid = article.find(".//PMID")
print(pmid.text, "-", (title.text or "")[:60])
etree: Summaries Without Full Records
from Bio import Entrez
handle = Entrez.esummary(db="nucleotide", id=["NC_000913.3"])
summaries = Entrez.read(handle)
handle.close()
doc = summaries["DocumentSummary"][0]
print(doc["Title"][:80])
print(doc["Caption"])
Rate Limits and Politeness
- Without an API key: 3 requests/second; with a key: 10/second.
- Always close() handles (use try/finally or context managers).
- Cache downloaded files - do not re-fetch large genomes on every run.
Summary
Bio.Entrez queries NCBI: esearch finds IDs, efetch downloads records (GenBank, FASTA, PubMed XML), and esummary gives lightweight metadata. Set Entrez.email and Entrez.api_key for higher rate limits, close handles after every call, and cache big downloads to be a good citizen of the Entrez network.