← All skills

mgnify

data

Find metagenome studies, samples and analyses in EBI MGnify by biome, then get taxonomic (SSU/LSU/ITS) and functional (InterPro, GO, KEGG) profiles and MAG catalogues, keyed on MGYS/MGYA/MGYG and ENA accessions — one pipeline version at a time.

MGnify — metagenome analyses and genome catalogues

MGnify (EMBL-EBI) takes public metagenomic, metatranscriptomic and amplicon sequencing data from ENA, runs it through its own analysis pipelines, and serves the results: taxonomic profiles from rRNA reads, functional annotation of predicted proteins, assemblies, and biome-specific catalogues of metagenome-assembled genomes (MAGs). This skill gets those results onto disk, correctly labelled, and keeps two things from going wrong:

  1. A profile belongs to a pipeline version, not to a sample. The same sequencing run is often analysed more than once, years apart, against different reference databases. The numbers are not comparable, and the labels are not even spelled the same.
  2. The JSON annotation endpoints drop the identifiers. Functional counts come back keyed on description text, and two different Pfam families can share a description. Read the per-analysis summary files, which keep the accession, and join on that.

Nothing here needs an account, a key or a licence acceptance. Private (pre-release) data is reachable only with ENA Webin credentials and is out of scope. The raw reads themselves live in ENA — use ena for FASTQ. For what an InterPro or Pfam accession means, use interpro.

Terms. MGnify is covered by the EMBL-EBI Terms of Use (revised 14 October 2026, https://www.ebi.ac.uk/about/terms-of-use), which say that "Where EMBL-EBI presents scientific data generated by others, EMBL-EBI imposes no additional restriction on the use of the contributed data than those provided by the data owner". The data owners here are ENA submitters, and ENA's INSDC policy places no use restriction on public sequence records. Cite MGnify (Richardson et al. 2023) and, for genomes, the catalogue paper. Do not hammer the API: the same terms block users whose load "prevents, or is likely to prevent, EMBL-EBI providing services to others".

Which API: v2 now, v1 frozen

v2 — https://www.ebi.ac.uk/metagenomics/api/v2/ v1 — https://www.ebi.ac.uk/metagenomics/api/v1/
status current; OpenAPI spec at /api/v2/openapi.json deprecated June 2026, frozen; still answering on 2026-11-15
pipeline V6 analyses yes no — 404
response shape {"count": N, "items": [...]} JSON:API — data, links.next, meta.pagination
page size cap 100 (larger values silently clamp to 100) 250 (larger values silently clamp to 250)
typical latency, 2026-11-15 0.6 – 4 s 3 – 18 s per call; one reverse lookup returned 502 after 32 s
per-analysis InterPro/GO/KEGG as JSON with accessions no — see Functional annotations yes, for V5 and earlier

MGnify's own documentation (https://docs.mgnify.org/src/docs/api.html) says v1 "will be turned off no earlier than September 1st 2026, but will serve frozen data that does not include MGnify V6 analyses". Build on v2. Use v1 only where this page says v2 cannot answer, and expect it to disappear.

curl -s "https://www.ebi.ac.uk/metagenomics/api/v2/studies/insdc/PRJNA479721"
echo
curl -s -o /dev/null -w "v1 says %{http_code} for a study added after the freeze\n" \
  "https://www.ebi.ac.uk/metagenomics/api/v1/studies/MGYS00010397"

Prints {"accession": "MGYS00010397"} then v1 says 404 ....

Copy paths from the OpenAPI spec exactly — a trailing slash is not optional in one direction. The spec writes most list routes with a slash (studies/, runs/{acc}/analyses/, runs/{acc}/assemblies/) and detail routes without (analyses/MGYA00592887), but not consistently: assemblies/{acc}/analyses is a list route with no slash.

  • A slash the spec does not have gives an HTML 404 page: analyses/MGYA00592887/, assemblies/ERZ3898142/analyses/.
  • A slash the spec has, left off, usually costs a 301 redirect that clients follow: studies?page_size=1 and runs/ERR4029720/assemblies both answer 200 JSON after one hop.
  • Except where the slashless path is another route. genomes/catalogues matches genomes/{accession} and returns JSON {"detail": "Not Found"} — read as a genome called "catalogues".

The body type tells you which mistake you made: HTML means a route that does not exist, JSON detail means a route that exists and a record that does not.

Paging

v2 has no next link. Read count, request page=1, 2, ... with page_size=100, and stop when you have count items. A page past the end returns 200 with an empty items list, not a 404, so a loop that waits for an error never ends. Every block below uses this helper:

import json, time, urllib.error, urllib.parse, urllib.request

API = "https://www.ebi.ac.uk/metagenomics/api/v2/"

def mg(path, **params):
    """GET one v2 endpoint. Retries the gateway errors EBI returns under load."""
    url = API + path + ("?" + urllib.parse.urlencode(params) if params else "")
    for attempt in range(4):
        try:
            with urllib.request.urlopen(url, timeout=120) as r:
                return json.loads(r.read())
        except urllib.error.HTTPError as e:
            if e.code in (502, 503, 504) and attempt < 3:
                time.sleep(5 * (attempt + 1))
                continue
            raise

def pages(path, **params):
    """Yield every item of a v2 list endpoint, checking the total against count."""
    page, got = 1, 0
    while True:
        j = mg(path, page=page, page_size=100, **params)
        yield from j["items"]
        got += len(j["items"])
        if not j["items"] or got >= j["count"]:
            if got != j["count"]:
                raise RuntimeError(f"{path}: got {got} of {j['count']}")
            return
        page += 1

print(mg("studies/", page_size=1)["count"], "studies;",
      mg("analyses/", page_size=1)["count"], "analyses")

Accessions, and how they connect

prefix what example
MGYS MGnify study (wraps one ENA study) MGYS00010397
MGYA one analysis — one run or one assembly, through one pipeline version MGYA01020362
MGYG genome in a catalogue (a species representative, in the API) MGYG000000001
ERZ assembly, an ENA analysis object ERZ3898142
PRJEB/PRJNA, ERP/SRP ENA/INSDC study PRJNA479721, SRP152093
ERR/SRR/DRR sequencing run SRR7760815
SAMEA/SAMN, ERS/SRS sample SAMEA6787325

Look things up by identifier, never by title. studies/insdc/{acc} takes either the BioProject or the secondary study accession and returns the MGYS; samples/{acc} takes either SAMEA6787325 or ERS4515003; runs/{acc} takes the run accession. A study's ena_accessions list holds both forms, in no fixed order.

A run's analyses are in two places. runs/{run}/analyses/ lists analyses of the reads. An analysis of an assembly built from those reads hangs off the assembly instead, and often belongs to a different MGYS (a third-party assembly study). ERR4029720 has zero analyses under runs/ and one, MGYA00592887, under its assembly:

def analyses_for_run(run):
    found = list(pages(f"runs/{run}/analyses/"))
    for asm in pages(f"runs/{run}/assemblies/"):
        found += list(pages(f"assemblies/{asm['accession']}/analyses"))   # no slash, per the spec
    return found

for run in ["SRR7760815", "ERR4029720"]:
    for a in analyses_for_run(run):
        print(run, a["accession"], a["pipeline_version"], a["experiment_type"],
              "study", a["study_accession"])

Find studies by biome

Biomes are colon-joined lineages from the GOLD-derived tree — root:Host-associated:Human:Digestive system, root:Environmental:Aquatic:Marine. Filters match the lineage and all its descendants, case-insensitively. Three traps:

  • An unknown lineage returns count: 0, not an error. root:Host-associated:Human:Gut and a bare Digestive system both answer 200 with zero studies. Check the string against biomes/ first, so "no data" and "wrong spelling" are not the same answer.
  • Sample biomes are mostly empty. Across the first page of samples of 30 human digestive studies, 1,801 of 1,801 samples had biome: null, so samples/?biome_lineage= finds 7,975 samples for a biome whose studies hold far more. Filter studies by biome, then walk each study's samples and analyses.
  • Genome biomes are coarser. Human gut MAGs sit at ...:Digestive system:Large intestine; asking genomes/ for ...:Large intestine:Fecal returns zero.
import collections

LINEAGE = "root:Host-associated:Human:Digestive system"
tree = [b["lineage"] for b in pages("biomes/", biome_lineage=LINEAGE)]
if not tree:
    raise SystemExit(f"{LINEAGE!r} is not an MGnify biome — browse {API}biomes/")
print(len(tree), "biomes under", LINEAGE)

studies = list(pages("studies/", biome_lineage=LINEAGE))
print(len(studies), "studies")
print(collections.Counter(s["biome"]["lineage"].removeprefix(LINEAGE) or "(itself)"
                          for s in studies).most_common(5))
print(studies[0]["accession"], studies[0]["ena_accessions"], studies[0]["title"][:60])

has_analyses_from_pipeline on studies/ is not a reliable filter. On 2026-11-15, V1, V2, V3, V4 and V4.1 each returned all 5,749 studies, V5 returned 59, and V6, V6.1 and V6.2 each returned the same 173. Read pipeline_version on each analysis instead.

One analysis: what it is and what it holds

analyses/{MGYA} returns the run or assembly, the sample, pipeline_version (V1 … V5, V6, V6.1, V6.2), experiment_type (Amplicon, Metagenomic, Metatranscriptomic, Assembly, ...), results_dir, and downloads — the list of files. The list endpoints omit downloads; only the detail endpoint carries it.

Each download has download_group, file_type, alias and url. Fetch url, and name the file after the URL, not the alias. For V5 and earlier the alias is a legacy display name that does not exist on the server: MGYA00592887 lists ERZ3898142_FASTA_InterPro.csv, and the file behind it is functional-annotation/ERZ3898142_FASTA.summary.ips. Building results_dir + alias gives a 404. For V6 the alias is sometimes just a label (motus, silva-ssu). file_size_bytes was null on every download checked.

What the files are depends on pipeline and experiment type:

taxonomy functional
V4.1 / V5 amplicon SSU/LSU (and ITS) OTU tables: *_OTU.tsv, .biom, MAPseq .mseq none
V1 – V4.1 metagenomic, assembly SSU/LSU OTU tables (V4.x), QIIME OTU table (V1) GO and GO-slim summaries (*_summary.go) and raw InterProScan matches only
V5 metagenomic, assembly same, plus SSU/LSU .mseq.tsv with an NCBI taxid column InterPro, GO, GO-slim, Pfam, KO, KEGG modules (.summary.*, headerless CSV)
V6 amplicon closed-reference SILVA-SSU, PR2, UNITE, ITSoneDB; DADA2 ASVs against SILVA and PR2 none
V6 metagenomic (raw reads) mOTUs3, SILVA-SSU, SILVA-LSU (*.txt.gz, Krona text) none by default — functional profiling of reads is switched off in V6
V6 assembly per-contig taxonomy with NCBI taxid lineages, Krona text InterPro, Pfam, GO, GO-slim, KO, KEGG modules, Rhea, eggNOG, dbCAN, antiSMASH (*_summary.tsv.gz, with headers)

So a V6 raw-reads analysis has no InterPro or GO profile at all. If you need function for a V6 dataset, look for its assembly analysis.

Taxonomic profiles

analyses/{MGYA}/annotations/{type} serves counts per taxon as JSON when type is one of taxonomies__ssu, taxonomies__lsu, taxonomies__unite, taxonomies__its_one_db, taxonomies__pr2, taxonomies__dada2_silva or taxonomies__dada2_pr2. The one other value the spec allows, pfams, is functional: its rows are description and count with organism: null (next section). analyses/{MGYA}/annotations with no type is not a list — it returns the whole analysis record (downloads included), with an annotations dict nested inside holding pfams, interpros and taxonomies (ssu, lsu, pr2, unite, its_one_db, each a list or null).

def taxa(mgya, kind="ssu"):
    return {r["organism"]: r["count"]
            for r in pages(f"analyses/{mgya}/annotations/taxonomies__{kind}")}

for mgya in ["MGYA00779426", "MGYA01012616"]:
    t = taxa(mgya)
    top = sorted(t.items(), key=lambda kv: -kv[1])[:3]
    print(mgya, len(t), "taxa,", sum(t.values()), "reads")
    for name, n in top:
        print(f"   {n:>7}  {name}")

Two things to notice in what comes back. The lineage grammar changes between pipelines: V4.1 and V5 write Bacteria::Proteobacteria:Alphaproteobacteria|5.0, ending in the pipeline version; V6 writes sk__Bacteria;k__;p__Actinomycetota;.... And there is no taxon identifier in the JSON. Where you need one — to join against NCBI Taxonomy, or any other source — read the file instead: V5 SSU/LSU summaries carry an NCBI taxid column (taxonomy-summary/SSU/*_SSU.fasta.mseq.tsv), and V6 assembly analyses carry per-contig NCBI taxid lineages (*_contigs_taxonomy.tsv.gz). V6 raw-read profiles (*_silva-ssu.txt.gz, *_motus.txt.gz) carry names only.

Functional annotations — files, not JSON

The JSON annotation endpoints return descriptions without accessions. For the V6 assembly analysis MGYA01030663, annotations/pfams returns two rows that read "Reverse transcriptase (RNA-dependent DNA polymerase)", 266 and 254. Those are two different families — PF00078 and PF07727 — and only the summary file says so. Key any dict on the description and one family silently overwrites the other; merge across samples on it and you add two families together. interpros has no route of its own (annotations/interpros is a 422); it appears only inside the no-type annotations record. pfams and interpros came back empty for every V≤5 and V6 raw-read analysis checked, even where the files exist.

So functional profiles come from the per-analysis summary files. Their formats differ by pipeline, which is the other reason to parse each version separately:

file (pick by url) V5 and earlier V6 assembly
InterPro *.summary.ips — count, IPR, description, no header (V5 only) *_interpro_summary.tsv.gz — header interpro_accession, description, count
GO *.summary.go (V5), *_summary.go (V1 – V4.1) — GO, term, namespace, count, no header *_go_summary.tsv.gz — header go, term, category, count
GO-slim *.summary.go_slim — as GO *_goslim_summary.tsv.gz — as GO
Pfam *.summary.pfam — count, PF, description, no header *_pfam_summary.tsv.gz — header pfam, description, count
KEGG orthologs *.summary.ko — count, K, description, no header *_ko_summary.tsv.gz — header ko, description, count
KEGG modules *.summary.kegg_pathways — header module_accession, completeness, ... *_kegg_modules_summary.tsv.gz — same header

Note the column order: the count is first in V5's InterPro, Pfam and KO files and last in its GO files. Before V5 there is no InterPro, Pfam or KO summary file at all — only GO, and the raw InterProScan matches (*_I5*.tsv.gz), which you would have to count yourself; frozen v1 still serves those InterPro counts (below) while it lasts.

import csv, gzip, io

def read_summary(url):
    """Return {accession: count} from any MGnify functional summary file, V4.1 to V6."""
    raw = urllib.request.urlopen(url, timeout=300).read()
    if url.endswith(".gz"):
        raw = gzip.decompress(raw)
    rows = list(csv.reader(io.StringIO(raw.decode()),
                           delimiter="\t" if ".tsv" in url else ","))
    if url.endswith((".summary.kegg_pathways", "_kegg_modules_summary.tsv.gz")):
        head, *body = rows                       # KEGG modules: completeness, not counts
        return {r[0]: float(r[head.index("completeness")]) for r in body}
    if url.endswith("_summary.tsv.gz"):          # V6: header, accession first, count last
        return {r[0]: int(r[-1]) for r in rows[1:]}
    if url.endswith(("summary.go", "summary.go_slim")):
        return {r[0]: int(r[-1]) for r in rows}  # V1-V5 GO: no header, count last
    return {r[1]: int(r[0]) for r in rows}       # V5 InterPro, Pfam, KO: no header, count first

def functional_urls(mgya):
    a = mg(f"analyses/{mgya}")
    pick = {}
    for d in a["downloads"]:
        name = d["url"].rsplit("/", 1)[1]
        for key, pats in {"interpro": (".summary.ips", "_interpro_summary.tsv.gz"),
                          "go": ("summary.go", "_go_summary.tsv.gz"),
                          "pfam": (".summary.pfam", "_pfam_summary.tsv.gz"),
                          "ko": (".summary.ko", "_ko_summary.tsv.gz"),
                          "kegg_modules": (".summary.kegg_pathways",
                                           "_kegg_modules_summary.tsv.gz")}.items():
            if name.endswith(pats):
                pick[key] = d["url"]
    return a["pipeline_version"], pick

for mgya in ["MGYA00592887", "MGYA01030663"]:
    version, urls = functional_urls(mgya)
    pf = read_summary(urls["pfam"])
    print(mgya, version, {k: len(read_summary(u)) for k, u in urls.items()})
    print("   PF00078", pf.get("PF00078"), "| PF07727", pf.get("PF07727"))

GO accessions here are joinable on the GO id itself; InterPro and Pfam accessions are what interpro takes. KEGG module rows report a completeness percentage, not a count, and that is why the parser keeps them apart.

Never pool abundances across pipeline versions

MGnify says it directly on its comparability page (https://docs.mgnify.org/src/docs/analysis/version6/analysis.html): results from different analysis versions "should not be assumed to be directly comparable". What that looks like on real data — the same run, SRR7760815, analysed twice:

MGYA00363409 (V4.1) MGYA00779426 (V5)
SSU reads assigned 317,350 275,867
SSU taxa 394 407
second most abundant label `Chloroplast 4.1`, 73,474 reads

It is not one unlucky run. SRR4070111 (marine sediment amplicon) has three analyses — V4.1 assigns 606,962 SSU reads across 348 taxa, V5 assigns 164,467 across 162, V6 assigns 255,140 across 218 — and no label appears verbatim in any two of them. SRR1204580 has four analyses (V1, V5 assembly, V6 reads, V6 assembly); its V1 analysis returns no SSU taxonomy through the API at all.

Different reference database (SILVA 132 for V5, 138.1 for V6) and a different classifier release (MAPseq 1.2.3 for V5, 2.1.1b for V6). The renames are not cosmetic either: V5 calls a phylum Actinobacteria and V6 calls it Actinomycetota, so a table pooled on names splits one taxon in two and a table pooled on counts compares different denominators. Even inside V6, V6, V6.1 and V6.2 are distinct analysis versions by MGnify's own rule (compare on the first two numbers; patch releases are comparable).

The rule for any multi-study table:

  • Group analyses by the exact pipeline_version string, and build one table per group.
  • Where a run has more than one analysis, choose one version for the whole table and say which. Do not average or sum the two.
  • Never merge taxa across groups by label. Re-classify from reads (ENA, via ena) under one pipeline if you need a single table.
by_version = collections.defaultdict(list)
for a in analyses_for_run("SRR7760815"):
    by_version[a["pipeline_version"]].append(a["accession"])
print(dict(by_version))

old, new = taxa("MGYA00363409"), taxa("MGYA00779426")
print("V4.1:", sum(old.values()), "reads,", len(old), "taxa; Chloroplast",
      old.get("Chloroplast|4.1"))
print("V5  :", sum(new.values()), "reads,", len(new), "taxa; Chloroplast",
      new.get("Chloroplast|5.0"))
print("labels shared verbatim:", len(set(old) & set(new)))

The last line prints 0: every V4.1 label ends |4.1 and every V5 label ends |5.0, so a naive outer join of the two profiles produces two disjoint halves rather than a comparison.

MGnify Genomes — catalogues of MAGs and isolates

genomes/catalogues/ lists the biome catalogues (20 on 2026-11-15: human gut, oral, skin and vaginal; mouse, pig, chicken, honeybee and two fish gut catalogues; cow and sheep rumen; soil, marine and marine sediment; three rhizospheres; and two eukaryote catalogues). For each, genome_count is the number of species representatives and unclustered_genome_count the number of genomes clustered into them.

  • The API serves species representatives only. human-gut-v3-0 has 6,461 in the API out of 286,621 genomes. The rest are in the catalogue's FTP genomes-all_metadata.tsv (114 MB for human gut v3.0, with an ftp:// column you should rewrite to https://).
  • The API serves one version of each catalogue. Human gut is v3-0 in v2 and v2-0-2 in frozen v1.
  • An MGYG accession survives a catalogue release; its taxonomy and its status may not. MGYG000000001 is g__GCA-900066495 under p__Firmicutes_A in human gut v2.0.2 and g__Romboutsia_E under p__Bacillota in v3.0 — same genome, a GTDB release apart. MGYG000000032 was a v2.0.2 species representative and is a 404 in v2: v3.0 replaced it with MGYG000917718. Each catalogue directory publishes replaced_species_reps.tsv and removed_species.tsv; check them before reporting a missing genome as absent.
  • Taxonomy is GTDB, as a lineage string; there is no NCBI taxid. Join to NCBI through ncbi_genome_accession or ena_genome_accession where present, not through the species name — GTDB placeholder names such as RGIG4708 sp905210855 match nothing in NCBI.
for cat in pages("genomes/catalogues/"):
    print(f"{cat['catalogue_id']:28} {cat['genome_count']:>6} reps of "
          f"{cat['unclustered_genome_count']:>7}  {cat['catalogue_type']}")

g = mg("genomes/MGYG000000001")
print(g["accession"], g["catalogue_id"], g["type"], g["completeness"], g["contamination"])
print("  ", g["taxon_lineage"])
ann = mg("genomes/MGYG000000001/annotations")["annotations"]
print("  ", {k: len(v) for k, v in ann.items()})

try:
    mg("genomes/MGYG000000032")
except urllib.error.HTTPError as e:
    rep = urllib.request.urlopen("https://ftp.ebi.ac.uk/pub/databases/metagenomics/"
                                 "mgnify_genomes/human-gut/v3.0/replaced_species_reps.tsv",
                                 timeout=120).read().decode()
    row = next(l.split("\t") for l in rep.splitlines() if l.startswith("MGYG000000032\t"))
    print("MGYG000000032:", e.code, "-> replaced by", row[1], "|", row[2])

Genome annotations (KEGG classes, KEGG modules, COG categories, antiSMASH clusters) are summaries; the per-genome files — .fna, .faa, .gff, _InterProScan.tsv, _eggNOG.tsv, _kegg_pathways.tsv, AMRFinderPlus, CRISPRCasFinder — are in the genome's downloads, and the file names differ by catalogue (.gz in human gut v3.0, uncompressed in soil v1.0). Take every URL from downloads.

Get the files

From a biome to files on disk, one pipeline version per directory, with a manifest that records which version every file came from. Set LINEAGE, VERSION and WANT. A kind in WANT that an analysis does not have is a warning naming the analysis, never a silent skip, and an analysis that matches nothing at all stops the run. The defaults take the summary tables (taxonomy and function) from the first three human-gut V5 assembly analyses found, which is a few MB.

import os, json, urllib.parse, urllib.request, warnings

LINEAGE = "root:Host-associated:Human:Digestive system"
VERSION = "V5"            # exact pipeline_version; never mix two in one table
EXPERIMENT = "Assembly"
N_ANALYSES = 3
WANT = {   # kind -> file-name endings, every spelling V1 to V6
    "interpro":     (".summary.ips", "_interpro_summary.tsv.gz"),
    "go":           (".summary.go", "_summary.go", "_go_summary.tsv.gz"),   # V5 . / V1-V4.1 _
    "go_slim":      (".summary.go_slim", "_summary.go_slim", "_goslim_summary.tsv.gz"),
    "pfam":         (".summary.pfam", "_pfam_summary.tsv.gz"),
    "ko":           (".summary.ko", "_ko_summary.tsv.gz"),
    "kegg_modules": (".summary.kegg_pathways", "_kegg_modules_summary.tsv.gz"),
    "taxonomy":     ("_SSU.fasta.mseq.tsv", "_LSU.fasta.mseq.tsv", "_contigs_taxonomy.tsv.gz"),
}
OUT = os.path.join("Data", "mgnify", VERSION)
os.makedirs(OUT, exist_ok=True)

manifest, chosen = [], []
for study in pages("studies/", biome_lineage=LINEAGE):
    for a in pages(f"studies/{study['accession']}/analyses/"):
        if a["pipeline_version"] == VERSION and a["experiment_type"] == EXPERIMENT:
            chosen.append((study, a))
            break                               # one analysis per study keeps samples independent
    if len(chosen) == N_ANALYSES:
        break

for study, a in chosen:
    detail = mg(f"analyses/{a['accession']}")
    assert detail["pipeline_version"] == VERSION
    d = os.path.join(OUT, a["accession"])
    os.makedirs(d, exist_ok=True)
    found = set()
    for f in detail["downloads"]:
        name = f["url"].rsplit("/", 1)[1]        # the alias is not the file name
        kind = next((k for k, ends in WANT.items() if name.endswith(ends)), None)
        if kind is None:
            continue
        found.add(kind)
        path = os.path.join(d, name)
        urllib.request.urlretrieve(f["url"], path)
        manifest.append({"study": study["accession"], "ena_study": study["ena_accessions"],
                         "analysis": a["accession"], "pipeline_version": VERSION,
                         "experiment_type": EXPERIMENT,
                         "run": (detail.get("run") or {}).get("accession"),
                         "assembly": (detail.get("assembly") or {}).get("accession"),
                         "sample": (detail.get("sample") or {}).get("accession"),
                         "kind": kind, "group": f["download_group"], "url": f["url"], "path": path,
                         "bytes": os.path.getsize(path)})
        print(f"{a['accession']}  {os.path.getsize(path):>9,}  {name}")
    if not found:
        raise RuntimeError(f"{a['accession']}: no download matched WANT — check the file names")
    missing = sorted(set(WANT) - found)
    if missing:                                  # e.g. V4.1 has no InterPro, Pfam or KO summary
        warnings.warn(f"{a['accession']} ({VERSION}): no {', '.join(missing)} file")

with open(os.path.join(OUT, "manifest.json"), "w") as fh:
    json.dump({"api": API, "biome": LINEAGE, "pipeline_version": VERSION,
               "files": manifest}, fh, indent=1)
print(len(manifest), "files from", len(chosen), "analyses ->", OUT)

For whole-study tables MGnify also publishes per-study summaries in each study's own downloads (study_summary.v5.0.*, study_summary.v6.amplicon); their group names carry the pipeline version, so the same one-version rule applies. For bulk transfers the same files are under https://ftp.ebi.ac.uk/pub/databases/metagenomics/mgnify_results/, arranged by ENA study accession and then by pipeline version. For alpha and beta diversity or ordination on the downloaded OTU tables, scikit-bio takes over — one pipeline version per table, as above.

Functional profiles from v1, while it lasts

For V5 and earlier, frozen v1 still serves per-analysis functional counts as JSON with accessions — interpro-identifiers, go-terms, go-slim, pfam-entries, kegg-orthologs, kegg-modules — paged JSON:API style. It is slow, deprecated, and has no V6. Prefer the files above; this is a fallback, not a route to build on.

curl -s "https://www.ebi.ac.uk/metagenomics/api/v1/analyses/MGYA00592887/go-terms?page_size=2" \
  | python3 -c 'import json,sys; j=json.load(sys.stdin)
print(j["meta"]["pagination"], j["links"]["next"])
for d in j["data"]: print(d["id"], d["attributes"]["count"], d["attributes"]["description"])'

What does not work

what what happens do instead
API v1 for anything V6 or added after mid-2026 404 v2
studies/?has_analyses_from_pipeline=V4.1 (and V1–V4) ignored — returns every study filter on each analysis's pipeline_version
samples/?biome_lineage=... misses most samples — their biome is null filter studies, then walk their samples
an unknown biome lineage 200, count: 0 validate against biomes/ first
results_dir + alias 404 for V5 and earlier use each download's url
annotations/pfams, or interpros in the annotations record, as a profile descriptions only, no accession; duplicates collide per-analysis summary files
annotations functional groups for V5 / V6 raw reads empty lists summary files; for V6, the assembly analysis
runs/{run}/analyses/ for assembly results empty runs/{run}/assemblies/, then assemblies/{ERZ}/analyses
a listed download url occasionally dead — all 32 for the V4 assembly analysis MGYA00139099 404, in v1 too (directory and file names disagree) check status per file; record the gap, do not substitute
annotations/taxonomies__ssu on a V1 analysis empty the V1 QIIME otu_table.biom download
analyses/{MGYA}/, assemblies/{ERZ}/analyses/ (a slash the spec lacks) HTML 404 page paths exactly as in openapi.json
genomes/catalogues (missing slash) JSON 404 — read as a genome accession genomes/catalogues/
page_size above 100 (v2) or 250 (v1) silently clamped page with count
a v2 page past the end 200, empty items stop on count
v1 annotations/go-terms/{GO}/analyses (reverse lookup) 502 after ~32 s no replacement in v2
a v2.0.2 human gut MGYG may 404 in v2 replaced_species_reps.tsv, removed_species.tsv
non-representative genomes in the API not served catalogue FTP genomes-all_metadata.tsv

Try it

Data — public MGnify records, no account, no key, served under the EMBL-EBI Terms of Use: run SRR7760815 (marine 16S amplicon, analysed as MGYA00363409 under V4.1 and MGYA00779426 under V5), the V6 assembly analysis MGYA01030663, the human digestive system biome, and human gut catalogue genomes MGYG000000001 and MGYG000000032. Last confirmed reachable 2026-11-15. The block routes through the traps above — two pipeline versions on one run, two Pfam families with one description, an unknown biome, a replaced genome — and asserts each, so a later simplification fails here first.

import collections, gzip, io, json, time, urllib.error, urllib.parse, urllib.request

API = "https://www.ebi.ac.uk/metagenomics/api/v2/"

def mg(path, **params):
    url = API + path + ("?" + urllib.parse.urlencode(params) if params else "")
    for attempt in range(4):
        try:
            with urllib.request.urlopen(url, timeout=120) as r:
                return json.loads(r.read())
        except urllib.error.HTTPError as e:
            if e.code in (502, 503, 504) and attempt < 3:
                time.sleep(5 * (attempt + 1)); continue
            raise

def pages(path, **params):
    page, got = 1, 0
    while True:
        j = mg(path, page=page, page_size=100, **params)
        yield from j["items"]
        got += len(j["items"])
        if not j["items"] or got >= j["count"]:
            assert got == j["count"], (path, got, j["count"])
            return
        page += 1

# 1. biome: real lineage finds studies; a plausible wrong one finds nothing, silently
LINEAGE = "root:Host-associated:Human:Digestive system"
studies = list(pages("studies/", biome_lineage=LINEAGE))
assert studies and all(s["biome"]["lineage"].lower().startswith(LINEAGE.lower()) for s in studies)
assert mg("studies/", biome_lineage="root:Host-associated:Human:Gut")["count"] == 0
print("human digestive studies:", len(studies))

# 2. one run, two pipeline versions: never pooled
runs = {a["pipeline_version"]: a["accession"] for a in pages("runs/SRR7760815/analyses/")}
assert {"V4.1": "MGYA00363409", "V5": "MGYA00779426"}.items() <= runs.items(), runs
ssu = {v: {r["organism"]: r["count"]
           for r in pages(f"analyses/{runs[v]}/annotations/taxonomies__ssu")}
       for v in ("V4.1", "V5")}
assert all(k.endswith("|4.1") for k in ssu["V4.1"]) and all(k.endswith("|5.0") for k in ssu["V5"])
assert not set(ssu["V4.1"]) & set(ssu["V5"])          # no label is shared verbatim
assert "Chloroplast|4.1" in ssu["V4.1"] and "Chloroplast|5.0" not in ssu["V5"]
for v, t in ssu.items():
    print(f"SRR7760815 {v}: {sum(t.values())} SSU reads, {len(t)} taxa")
three = {a["pipeline_version"]: a["accession"] for a in pages("runs/SRR4070111/analyses/")}
assert {"V4.1", "V5", "V6"} <= set(three), three
labels = {v: set(r["organism"] for r in pages(f"analyses/{three[v]}/annotations/taxonomies__ssu"))
          for v in ("V4.1", "V5", "V6")}
assert not (labels["V4.1"] & labels["V5"] or labels["V5"] & labels["V6"] or labels["V4.1"] & labels["V6"])
print("SRR4070111:", {v: len(l) for v, l in labels.items()}, "taxa; 0 labels shared")

# 3. functional profile: JSON loses the accession, the file keeps it
detail = mg("analyses/MGYA01030663")
assert detail["pipeline_version"] == "V6" and detail["experiment_type"] == "Assembly"
js = list(pages("analyses/MGYA01030663/annotations/pfams"))
assert all("accession" not in r for r in js)
descs = collections.Counter(r["description"] for r in js)
url = next(d["url"] for d in detail["downloads"] if d["url"].endswith("_pfam_summary.tsv.gz"))
rows = gzip.decompress(urllib.request.urlopen(url, timeout=300).read()).decode().splitlines()
assert rows[0].split("\t") == ["pfam", "description", "count"]
pf = {r.split("\t")[0]: (r.split("\t")[1], int(r.split("\t")[2])) for r in rows[1:]}
rt = "Reverse transcriptase (RNA-dependent DNA polymerase)"
assert descs[rt] == 2 and pf["PF00078"][0] == pf["PF07727"][0] == rt
assert len(pf) == len(js)
print(f"MGYA01030663: {len(pf)} Pfam families; '{rt[:20]}...' is PF00078 ({pf['PF00078'][1]})"
      f" and PF07727 ({pf['PF07727'][1]})")

# 4. the alias is not the file name (V5)
v5 = mg("analyses/MGYA00592887")
ips = next(d for d in v5["downloads"] if d["url"].endswith(".summary.ips"))
assert ips["alias"] != ips["url"].rsplit("/", 1)[1]
print("alias", ips["alias"], "-> file", ips["url"].rsplit("/", 1)[1])

# 5. genomes: a species rep, and one replaced in the current catalogue
g = mg("genomes/MGYG000000001")
assert g["catalogue_id"].startswith("human-gut") and g["taxon_lineage"].startswith("d__Bacteria")
try:
    mg("genomes/MGYG000000032"); raise AssertionError("MGYG000000032 is back")
except urllib.error.HTTPError as e:
    assert e.code == 404
rep = urllib.request.urlopen("https://ftp.ebi.ac.uk/pub/databases/metagenomics/mgnify_genomes/"
                             "human-gut/v3.0/replaced_species_reps.tsv", timeout=120).read().decode()
new = next(l.split("\t")[1] for l in rep.splitlines() if l.startswith("MGYG000000032\t"))
assert mg(f"genomes/{new}")["accession"] == new
print("MGYG000000001", g["catalogue_id"], g["taxon_lineage"].split(";")[-1],
      "| MGYG000000032 -> 404, replaced by", new)

Expect

Invariants — these hold whatever MGnify adds or reruns, and a failure means the skill is wrong:

  • Every study returned for a biome lies on or under that lineage; a near-miss lineage returns count: 0 with status 200.
  • SRR7760815 has a V4.1 and a V5 analysis (a later rerun may add more), their SSU labels end in |4.1 and |5.0, no label is shared verbatim, and Chloroplast exists only under V4.1. SRR4070111 has V4.1, V5 and V6 analyses and no SSU label is shared by any two.
  • The JSON Pfam rows have no accession; the summary file has a header, as many families as the JSON has rows, and two distinct accessions behind one description.
  • A V5 download's alias differs from its file name.
  • MGYG000000032 is 404 in v2 and resolves through replaced_species_reps.tsv to a genome that is served.

Observed 2026-11-15 against API v2.0.0 — these move as MGnify adds studies and reruns analyses, so a mismatch is drift to investigate, not a failure:

human digestive studies: 707
SRR7760815 V4.1: 317350 SSU reads, 394 taxa
SRR7760815 V5: 275867 SSU reads, 407 taxa
SRR4070111: {'V4.1': 348, 'V5': 162, 'V6': 218} taxa; 0 labels shared
MGYA01030663: 923 Pfam families; 'Reverse transcriptas...' is PF00078 (266) and PF07727 (254)
alias ERZ3898142_FASTA_InterPro.csv -> file ERZ3898142_FASTA.summary.ips
MGYG000000001 human-gut-v3-0 s__Romboutsia_E sp902362365 | MGYG000000032 -> 404, replaced by MGYG000917718

The block makes about 40 requests and took 45 s from a cold directory.

Sources