Skip to content

API reference

Auto-generated from the package docstrings.

Fetching data

ibge_variables

ibge_variables(aggregate: int, variable: Any = None, periods: Any = -6, localities: Localities = 'BR', classification: Optional[Mapping[str, Any]] = None, view: Optional[str] = None, validate: bool = True, chunk: Any = True) -> pd.DataFrame

Retrieve variable results from an aggregate (the package's main function).

Parameters:

Name Type Description Default
aggregate int

Numeric aggregate identifier (SIDRA table).

required
variable Any

None (default standard variables), an id or list of ids, or "all" (include generated percentage variables).

None
periods Any

Negative int for last-N (default -6), a value/list, or a range string like "201701-201712".

-6
localities Localities

"BR" (default), a level code ("N3"), or a mapping such as {"N6": [3550308, 3304557]}.

'BR'
classification Optional[Mapping[str, Any]]

Mapping of classification id -> category id(s), or "all".

None
view Optional[str]

None (default), "OLAP" or "flat".

None
validate bool

If True (default), validate parameters against the aggregate metadata before querying.

True
chunk Any

Controls automatic splitting of large queries. The IBGE API rejects requests whose result is too large with an HTTP 500 error (the documented limit is 100,000 values, but in practice requests fail above about 50,000). True (default) estimates the result size (variables x periods x localities x categories) and, when it exceeds 50,000 values, transparently splits the query into multiple smaller requests (by periods, then by localities) and combines the results. False always performs a single request. A positive number works like True but with a custom per-request value limit.

True

Returns:

Type Description
DataFrame

Tidy (long) format: variable_id, variable_name, variable_unit, classification columns (when present), locality_id, locality_name, locality_level, period, value (string; use :func:ibgepy.parse_ibge_value).

Notes

Large requests can be slow on the server side: queries covering all municipalities (localities="N6", some 5,500 localities) may take one to several minutes per request to be answered by the IBGE API, even before any chunking. This is normal — the function is not hanging.

Source code in src/ibgepy/variables.py
def ibge_variables(
    aggregate: int,
    variable: Any = None,
    periods: Any = -6,
    localities: Localities = "BR",
    classification: Optional[Mapping[str, Any]] = None,
    view: Optional[str] = None,
    validate: bool = True,
    chunk: Any = True,
) -> pd.DataFrame:
    """Retrieve variable results from an aggregate (the package's main function).

    Parameters
    ----------
    aggregate:
        Numeric aggregate identifier (SIDRA table).
    variable:
        ``None`` (default standard variables), an id or list of ids, or
        ``"all"`` (include generated percentage variables).
    periods:
        Negative int for last-N (default ``-6``), a value/list, or a range
        string like ``"201701-201712"``.
    localities:
        ``"BR"`` (default), a level code (``"N3"``), or a mapping such as
        ``{"N6": [3550308, 3304557]}``.
    classification:
        Mapping of classification id -> category id(s), or ``"all"``.
    view:
        ``None`` (default), ``"OLAP"`` or ``"flat"``.
    validate:
        If ``True`` (default), validate parameters against the aggregate
        metadata before querying.
    chunk:
        Controls automatic splitting of large queries. The IBGE API rejects
        requests whose result is too large with an HTTP 500 error (the
        documented limit is 100,000 values, but in practice requests fail
        above about 50,000). ``True`` (default) estimates the result size
        (variables x periods x localities x categories) and, when it exceeds
        50,000 values, transparently splits the query into multiple smaller
        requests (by periods, then by localities) and combines the results.
        ``False`` always performs a single request. A positive number works
        like ``True`` but with a custom per-request value limit.

    Returns
    -------
    pandas.DataFrame
        Tidy (long) format: ``variable_id``, ``variable_name``,
        ``variable_unit``, classification columns (when present),
        ``locality_id``, ``locality_name``, ``locality_level``, ``period``,
        ``value`` (string; use :func:`ibgepy.parse_ibge_value`).

    Notes
    -----
    Large requests can be slow on the server side: queries covering all
    municipalities (``localities="N6"``, some 5,500 localities) may take one
    to several minutes *per request* to be answered by the IBGE API, even
    before any chunking. This is normal — the function is not hanging.
    """
    meta = None

    if validate:
        meta = get_cached_metadata(aggregate)
        validate_query(
            meta,
            localities=localities,
            periods=periods,
            variable=variable,
            classification=classification,
        )

    variable_str = format_variable(variable)
    periods_str = format_periods(periods)
    localities_str = format_localities(localities)
    classification_str = format_classification(classification)

    chunk_limit = resolve_chunk_limit(chunk)

    plan = None
    if chunk_limit is not None:
        plan = build_chunk_plan(
            aggregate,
            meta,
            variable=variable,
            periods=periods,
            localities=localities,
            classification=classification,
            limit=chunk_limit,
        )

    if plan is None:
        query = {
            "localidades": localities_str,
            "classificacao": classification_str,
            "view": view,
        }

        data = ibge_request(
            aggregate,
            "periodos",
            periods_str,
            "variaveis",
            variable_str,
            query=query,
            label=f"variables for aggregate {aggregate}",
            data_request=True,
        )

        result = _parse_variables(data, view=view)
    else:
        n_chunks = len(plan)
        _msg.step(
            f"Estimated result exceeds the API limit ({chunk_limit:.0f} values); "
            f"splitting into {n_chunks} request(s)."
        )

        pieces = []
        for i, ch in enumerate(plan, start=1):
            data = ibge_request(
                aggregate,
                "periodos",
                ch["periods_str"],
                "variaveis",
                variable_str,
                query={
                    "localidades": ch["localities_str"],
                    "classificacao": classification_str,
                    "view": view,
                },
                label=f"chunk {i}/{n_chunks} for aggregate {aggregate}",
                data_request=True,
            )
            pieces.append(_parse_variables(data, view=view))

        non_empty = [p for p in pieces if not p.empty]
        result = (
            pd.concat(non_empty, ignore_index=True) if non_empty else pd.DataFrame()
        )

    _msg.success(f"{len(result)} record(s) retrieved.")
    return result

ibge_aggregates

ibge_aggregates(period: Optional[str] = None, subject: Optional[int] = None, classification: Optional[int] = None, periodicity: Optional[str] = None, level: Optional[str] = None) -> pd.DataFrame

List available aggregates (tables), optionally filtered.

Results are cached in memory per unique parameter combination.

Parameters:

Name Type Description Default
period Optional[str]

Periodicity code followed by one or more period ids in brackets, e.g. "P5[202001]" or "P1[2019,2020]".

None
subject Optional[int]

Numeric subject code (see :func:ibge_subjects), e.g. 70.

None
classification Optional[int]

Numeric classification code, e.g. 12026.

None
periodicity Optional[str]

Periodicity code: "P1" (annual), "P5" (monthly), "P8" (semi-annual), "P9" (quarterly), "P13" (rolling quarter); see :data:PERIODICITIES for the codes observed in the catalog.

None
level Optional[str]

Geographic level: "N1" (Brazil), "N3" (state), "N6" (municipality), ...

None
All
required
request
required
because
required
whole
required
aggregate
required
Returns
required
Source code in src/ibgepy/aggregates.py
def ibge_aggregates(
    period: Optional[str] = None,
    subject: Optional[int] = None,
    classification: Optional[int] = None,
    periodicity: Optional[str] = None,
    level: Optional[str] = None,
) -> pd.DataFrame:
    """List available aggregates (tables), optionally filtered.

    Results are cached in memory per unique parameter combination.

    Parameters
    ----------
    period
        Periodicity code followed by one or more period ids in brackets,
        e.g. ``"P5[202001]"`` or ``"P1[2019,2020]"``.
    subject
        Numeric subject code (see :func:`ibge_subjects`), e.g. ``70``.
    classification
        Numeric classification code, e.g. ``12026``.
    periodicity
        Periodicity code: ``"P1"`` (annual), ``"P5"`` (monthly), ``"P8"``
        (semi-annual), ``"P9"`` (quarterly), ``"P13"`` (rolling quarter);
        see :data:`PERIODICITIES` for the codes observed in the catalog.
    level
        Geographic level: ``"N1"`` (Brazil), ``"N3"`` (state), ``"N6"``
        (municipality), ...

    All filters are checked for the format the API expects before the
    request, because the API ignores what it cannot parse (returning the
    whole catalog) or answers HTTP 500. A well-formed filter that matches no
    aggregate returns an empty DataFrame with a warning.

    Returns a DataFrame with columns ``survey_id``, ``survey_name``,
    ``aggregate_id``, ``aggregate_name``.
    """
    for name, value in (
        ("period", period),
        ("subject", subject),
        ("classification", classification),
        ("periodicity", periodicity),
        ("level", level),
    ):
        _check_filter(value, name)

    params = {
        "periodo": period,
        "assunto": subject,
        "classificacao": classification,
        "periodicidade": periodicity,
        "nivel": level,
    }
    key = _cache_key(params)
    cached = _cache._AGG_META_CACHE.get(key)
    if cached is not None:
        _msg.success(f"{len(cached)} aggregate(s) found (cached).")
        return cached

    query = {k: v for k, v in params.items() if v is not None}
    data = ibge_request(query=query, label="aggregates")

    rows = []
    for survey in data:
        aggregates = survey.get("agregados") or []
        for ag in aggregates:
            rows.append(
                {
                    "survey_id": pluck_str(survey, "id"),
                    "survey_name": pluck_str(survey, "nome"),
                    "aggregate_id": pluck_str(ag, "id"),
                    "aggregate_name": pluck_str(ag, "nome"),
                }
            )

    result = pd.DataFrame(
        rows, columns=["survey_id", "survey_name", "aggregate_id", "aggregate_name"]
    )
    _cache._AGG_META_CACHE[key] = result
    if len(result) == 0:
        _msg.warn("No aggregates found for the given filters.")
    else:
        _msg.success(f"{len(result)} aggregate(s) found.")
    return result

Metadata & discovery

ibge_metadata

ibge_metadata(aggregate: int) -> IbgeMetadata

Retrieve complete metadata for an aggregate (cached per session).

Source code in src/ibgepy/metadata.py
def ibge_metadata(aggregate: int) -> IbgeMetadata:
    """Retrieve complete metadata for an aggregate (cached per session)."""
    cache_key = f"meta_{aggregate}"
    cached = _cache._AGG_META_CACHE.get(cache_key)
    if cached is not None:
        _report(cached, aggregate, cached_flag=True)
        return cached

    data = ibge_request(aggregate, "metadados", label=f"metadata for aggregate {aggregate}")
    if isinstance(data, list) and len(data) >= 1:
        data = data[0]

    # --- Variables ---
    vars_raw = data.get("variaveis") or []
    if vars_raw:
        variables = pd.DataFrame(
            [
                {
                    "id": pluck_str(v, "id"),
                    "name": pluck_str(v, "nome"),
                    "unit": pluck_str(v, "unidade"),
                }
                for v in vars_raw
            ]
        )
    else:
        variables = pd.DataFrame(columns=["id", "name", "unit"])

    # --- Classifications (with ALL categories) ---
    cls_raw = data.get("classificacoes") or []
    cls_rows = []
    for cls in cls_raw:
        cats_raw = cls.get("categorias") or []
        if cats_raw:
            categories = pd.DataFrame(
                [
                    {
                        "category_id": pluck_str(cat, "id"),
                        "category_name": pluck_str(cat, "nome"),
                        "category_unit": pluck_str(cat, "unidade"),
                        "category_level": pluck_str(cat, "nivel"),
                    }
                    for cat in cats_raw
                ]
            )
        else:
            categories = _empty_categories()
        cls_rows.append(
            {
                "id": pluck_str(cls, "id"),
                "name": pluck_str(cls, "nome"),
                "categories": categories,
            }
        )
    classifications = (
        pd.DataFrame(cls_rows)
        if cls_rows
        else pd.DataFrame(columns=["id", "name", "categories"])
    )

    # --- Territorial level ---
    nt_raw = data.get("nivelTerritorial") or {}
    territorial_level = {
        "administrative": list(nt_raw.get("Administrativo") or []),
        "special": list(nt_raw.get("Especial") or []),
        "ibge": list(nt_raw.get("IBGE") or []),
    }

    # --- Periodicity ---
    per_raw = data.get("periodicidade") or {}
    periodicity = {
        "frequency": per_raw.get("frequencia"),
        "start": per_raw.get("inicio"),
        "end": per_raw.get("fim"),
    }

    result = IbgeMetadata(
        id=data.get("id"),
        name=data.get("nome"),
        url=data.get("URL"),
        survey=data.get("pesquisa"),
        subject=data.get("assunto"),
        periodicity=periodicity,
        territorial_level=territorial_level,
        variables=variables,
        classifications=classifications,
    )

    _cache._AGG_META_CACHE[cache_key] = result
    _report(result, aggregate, cached_flag=False)
    return result

ibge_periods

ibge_periods(aggregate: int) -> pd.DataFrame

Retrieve available periods for an aggregate.

Returns a DataFrame with columns id, literal, modification.

Source code in src/ibgepy/periods.py
def ibge_periods(aggregate: int) -> pd.DataFrame:
    """Retrieve available periods for an aggregate.

    Returns a DataFrame with columns ``id``, ``literal``, ``modification``.
    """
    data = ibge_request(aggregate, "periodos", label=f"periods for aggregate {aggregate}")

    rows = []
    for p in data:
        lits = p.get("literals") or []
        lit_str = " / ".join(str(x) for x in lits) if lits else None
        rows.append(
            {
                "id": pluck_str(p, "id"),
                "literal": lit_str,
                "modification": pluck_str(p, "modificacao"),
            }
        )

    result = pd.DataFrame(rows, columns=["id", "literal", "modification"])
    _msg.success(f"{len(result)} period(s) found.")
    return result

ibge_localities

ibge_localities(aggregate: int, level: Union[str, Sequence[str]] = 'N6', validate: bool = True) -> pd.DataFrame

Retrieve available localities for an aggregate.

level may be a single level ("N6") or a list (["N6", "N7"]). With several levels one request is made per level and the results are concatenated: the API's own multi-level endpoint returns an empty list as soon as one of the levels has no localities for the aggregate.

Returns a DataFrame with columns id, name, level_id, level_name (empty, but with those columns, when nothing is found).

Source code in src/ibgepy/localities.py
def ibge_localities(
    aggregate: int,
    level: Union[str, Sequence[str]] = "N6",
    validate: bool = True,
) -> pd.DataFrame:
    """Retrieve available localities for an aggregate.

    ``level`` may be a single level (``"N6"``) or a list (``["N6", "N7"]``).
    With several levels one request is made per level and the results are
    concatenated: the API's own multi-level endpoint returns an empty list
    as soon as one of the levels has no localities for the aggregate.

    Returns a DataFrame with columns ``id``, ``name``, ``level_id``,
    ``level_name`` (empty, but with those columns, when nothing is found).
    """
    if validate:
        meta = get_cached_metadata(aggregate)
        validate_query(meta, level=level)

    levels = [level] if isinstance(level, str) else list(level)

    rows = []
    for lvl in levels:
        data = ibge_request(
            aggregate, "localidades", lvl, label=f"{lvl} localities for aggregate {aggregate}"
        )
        rows.extend(
            {
                "id": pluck_str(loc, "id"),
                "name": pluck_str(loc, "nome"),
                "level_id": pluck_str(loc, "nivel", "id"),
                "level_name": pluck_str(loc, "nivel", "nome"),
            }
            for loc in data
        )
    result = pd.DataFrame(rows, columns=["id", "name", "level_id", "level_name"])
    if len(result) == 0:
        _msg.warn(f"No localities found for aggregate {aggregate} at level {levels}.")
    else:
        _msg.success(f"{len(result)} localit(y/ies) found.")
    return result

ibge_subjects

ibge_subjects(pattern: Optional[str] = None, ignore_case: bool = True) -> pd.DataFrame

Return IBGE subject codes and descriptions (built-in, no API call).

Parameters:

Name Type Description Default
pattern Optional[str]

Optional regular expression to filter subject descriptions. If None (default), the full table is returned.

None
ignore_case bool

If True (default), matching is case-insensitive.

True

Returns:

Type Description
DataFrame

Columns id (int) and name (str).

Source code in src/ibgepy/subjects.py
def ibge_subjects(pattern: Optional[str] = None, ignore_case: bool = True) -> pd.DataFrame:
    """Return IBGE subject codes and descriptions (built-in, no API call).

    Parameters
    ----------
    pattern:
        Optional regular expression to filter subject descriptions. If
        ``None`` (default), the full table is returned.
    ignore_case:
        If ``True`` (default), matching is case-insensitive.

    Returns
    -------
    pandas.DataFrame
        Columns ``id`` (int) and ``name`` (str).
    """
    df = pd.DataFrame(_SUBJECTS, columns=["id", "name"])

    if pattern:
        flags = re.IGNORECASE if ignore_case else 0
        regex = re.compile(pattern, flags)
        df = df[df["name"].apply(lambda s: regex.search(s) is not None)].reset_index(drop=True)
        _msg.success(f"{len(df)} subject(s) matched pattern {pattern!r}.")
    else:
        _msg.success(f"{len(df)} subjects loaded.")

    return df

Survey catalog

ibge_surveys

ibge_surveys(thematic_classifications: bool = True) -> pd.DataFrame

List the full catalog of IBGE surveys with institutional metadata.

Uses the Metadata API (v2). If thematic_classifications is True (default), a thematic_classifications column holds, per row, a nested DataFrame of classification details.

Source code in src/ibgepy/surveys.py
def ibge_surveys(thematic_classifications: bool = True) -> pd.DataFrame:
    """List the full catalog of IBGE surveys with institutional metadata.

    Uses the Metadata API (v2). If ``thematic_classifications`` is ``True``
    (default), a ``thematic_classifications`` column holds, per row, a nested
    DataFrame of classification details.
    """
    data = metadata_request("pesquisas", label="survey catalog")
    rows = []
    for s in data:
        row = {
            "id": pluck_str(s, "codigo"),
            "name": pluck_str(s, "nome"),
            "name_en": pluck_str(s, "nome_ingles"),
            "status": pluck_str(s, "situacao"),
            "category": pluck_str(s, "categoria"),
            "collection_frequency": pluck_str(s, "periodicidade_coleta"),
            "publication_frequency": pluck_str(s, "periodicidade_divulgacao"),
        }
        if thematic_classifications:
            cls_raw = s.get("classificacoes_tematicas") or []
            row["thematic_classifications"] = pd.DataFrame(
                [
                    {
                        "name": pluck_str(cls, "nome"),
                        "name_en": pluck_str(cls, "nome_ingles"),
                        "domain": pluck_str(cls, "dominio"),
                        "domain_en": pluck_str(cls, "dominio_ingles"),
                        "description": pluck_str(cls, "descricao"),
                    }
                    for cls in cls_raw
                ],
                columns=["name", "name_en", "domain", "domain_en", "description"],
            )
        rows.append(row)

    result = pd.DataFrame(rows)
    _msg.success(f"{len(result)} survey(s) found.")
    return result

ibge_survey_periods

ibge_survey_periods(survey: str) -> pd.DataFrame

List the periods (year/month) for which a survey has metadata.

The survey code is validated against the IBGE catalog first; invalid codes raise a helpful error with suggestions. Returns a DataFrame with columns year, month (<NA> for structural surveys), order.

Source code in src/ibgepy/surveys.py
def ibge_survey_periods(survey: str) -> pd.DataFrame:
    """List the periods (year/month) for which a survey has metadata.

    The survey code is validated against the IBGE catalog first; invalid
    codes raise a helpful error with suggestions. Returns a DataFrame with
    columns ``year``, ``month`` (``<NA>`` for structural surveys), ``order``.
    """
    _validate_survey_code(survey)
    result = _get_survey_periods(survey)
    _msg.success(f"{len(result)} period(s) found for survey {survey!r}.")
    return result

ibge_survey_metadata

ibge_survey_metadata(survey: str, year: int, month: Optional[int] = None, order: int = 0) -> IbgeSurveyMetadata

Detailed metadata for a survey in a given reference period.

Both the survey code and the year/month combination are validated against the IBGE catalog before the request is sent.

Source code in src/ibgepy/surveys.py
def ibge_survey_metadata(
    survey: str,
    year: int,
    month: Optional[int] = None,
    order: int = 0,
) -> IbgeSurveyMetadata:
    """Detailed metadata for a survey in a given reference period.

    Both the survey code and the year/month combination are validated against
    the IBGE catalog before the request is sent.
    """
    if not isinstance(year, int):
        raise ValueError("`year` must be a single integer.")
    if month is not None and (not isinstance(month, int) or month < 1 or month > 12):
        raise ValueError("`month` must be an integer between 1 and 12.")

    _validate_survey_code(survey)
    _validate_survey_period(survey, year, month)

    path: List[Any] = [survey, int(year)]
    label = f"metadata for {survey} ({year}"
    if month is not None:
        path.append(int(month))
        label += f"/{month}"
    path.append(int(order))
    label += ")"

    data = metadata_request(*path, label=label)
    if isinstance(data, list) and len(data) >= 1:
        data = data[0]

    cls_raw = data.get("classificacoes_tematicas") or []
    thematic = pd.DataFrame(
        [{k: (None if v is None else str(v)) for k, v in cls.items()} for cls in cls_raw]
    )

    occurrences = data.get("ocorrencias_pesquisa") or []

    result = IbgeSurveyMetadata(
        status=data.get("situacao"),
        category=data.get("categoria"),
        type=data.get("tipo"),
        area=data.get("area"),
        acronym=data.get("sigla"),
        start_date=data.get("data_inicio"),
        deactivation_date=data.get("data_desativacao"),
        sidra_url=data.get("url-sidra"),
        concla_url=data.get("url-concla"),
        thematic_classifications=thematic,
        occurrences=occurrences,
    )
    _msg.success(f"Survey {survey!r} ({year}): {len(occurrences)} metadata occurrence(s).")
    return result

SIDRA URLs

parse_sidra_url

parse_sidra_url(url: str) -> SidraQuery

Convert a SIDRA API URL into a structured, name-enriched breakdown.

Source code in src/ibgepy/sidra_url.py
def parse_sidra_url(url: str) -> SidraQuery:
    """Convert a SIDRA API URL into a structured, name-enriched breakdown."""
    url = unquote(url)
    path = re.sub(r".*?/values/", "", url, flags=re.IGNORECASE)
    path = re.sub(r"\?.*", "", path)
    path = re.sub(r"/$", "", path)
    segments = path.split("/")

    aggregate_id: Optional[str] = None
    variables: List[str] = []
    periods = ""
    localities: List[Dict[str, str]] = []
    classifications: Dict[str, List[str]] = {}

    i = 0
    n = len(segments)
    while i < n:
        seg = segments[i]
        if seg == "t" and i + 1 < n:
            aggregate_id = segments[i + 1]
            i += 2
        elif re.fullmatch(r"n\d+", seg) and i + 1 < n:
            level = "N" + seg[1:]
            localities.append({"level": level, "codes": segments[i + 1]})
            i += 2
        elif seg == "v" and i + 1 < n:
            variables = segments[i + 1].split(",")
            i += 2
        elif seg == "p" and i + 1 < n:
            periods = segments[i + 1]
            i += 2
        elif re.fullmatch(r"c\d+", seg) and i + 1 < n:
            cls_id = seg[1:]
            classifications[cls_id] = segments[i + 1].split(",")
            i += 2
        else:
            i += 1

    if aggregate_id is None:
        raise ValueError(
            "Could not find an aggregate ID in the URL. "
            "Expected a SIDRA API URL with /t/{id} in the path."
        )

    meta = get_cached_metadata(int(aggregate_id))

    # --- Resolve variable names ---
    if variables and variables != ["allxp"]:
        meta_vars = meta.variables.set_index(meta.variables["id"].astype(str))
        var_rows = []
        for vid in variables:
            if vid in meta_vars.index:
                row = meta_vars.loc[vid]
                var_rows.append({"id": vid, "name": row["name"], "unit": row["unit"]})
            else:
                var_rows.append({"id": vid, "name": None, "unit": None})
        var_info = pd.DataFrame(var_rows, columns=["id", "name", "unit"])
    else:
        var_info = meta.variables.copy()

    # --- Resolve classification/category names ---
    cls_info = []
    for cls_id, cats in classifications.items():
        cls_match = meta.classifications[meta.classifications["id"].astype(str) == cls_id]
        cls_name = cls_match.iloc[0]["name"] if len(cls_match) else None
        if cats == ["all"]:
            cat_detail = pd.DataFrame(
                [{"category_id": "all", "category_name": "(all categories)"}]
            )
        elif len(cls_match):
            all_cats = cls_match.iloc[0]["categories"]
            lookup = all_cats.set_index(all_cats["category_id"].astype(str))
            cat_rows = []
            for cid in cats:
                if cid in lookup.index:
                    cat_rows.append(
                        {"category_id": cid, "category_name": lookup.loc[cid]["category_name"]}
                    )
                else:
                    cat_rows.append({"category_id": cid, "category_name": None})
            cat_detail = pd.DataFrame(cat_rows, columns=["category_id", "category_name"])
        else:
            cat_detail = pd.DataFrame(
                [{"category_id": c, "category_name": None} for c in cats]
            )
        cls_info.append({"id": cls_id, "name": cls_name, "categories": cat_detail})

    # --- Resolve locality level names ---
    loc_info = []
    for loc in localities:
        loc_info.append(
            {
                "level": loc["level"],
                "level_name": _LEVEL_NAMES.get(loc["level"], "unknown level"),
                "codes": loc["codes"],
            }
        )
    _warn_sidra_levels(meta, loc_info)

    ibger_call = _build_ibgepy_call(
        aggregate_id, list(var_info["id"]), periods, localities, classifications
    )

    return SidraQuery(
        aggregate={"id": aggregate_id, "name": meta.name},
        variables=var_info,
        periods=periods,
        localities=loc_info,
        classifications=cls_info,
        ibger_call=ibger_call,
        periodicity=meta.periodicity,
    )

fetch_sidra_url

fetch_sidra_url(url: str, validate: bool = True) -> pd.DataFrame

Parse a SIDRA API URL and fetch the data via :func:ibge_variables.

Source code in src/ibgepy/sidra_url.py
def fetch_sidra_url(url: str, validate: bool = True) -> pd.DataFrame:
    """Parse a SIDRA API URL and fetch the data via :func:`ibge_variables`."""
    from .variables import ibge_variables

    parsed = parse_sidra_url(url)

    # --- Build localities argument ---
    localities: Any = _localities_arg(parsed.localities)

    # --- Build classification argument ---
    classification: Optional[Dict[str, Any]] = None
    if parsed.classifications:
        classification = {}
        for cls in parsed.classifications:
            cats = list(cls["categories"]["category_id"])
            classification[str(cls["id"])] = (
                "all" if cats == ["all"] else [int(c) for c in cats]
            )

    # --- Build variable argument ---
    variable: Any = None
    if len(parsed.variables) > 0:
        ids = list(parsed.variables["id"])
        if ids not in (["allxp"], ["all"]):
            variable = [int(v) for v in ids]

    # --- Build periods argument ---
    if parsed.periods:
        m = re.match(r"^last\s+", parsed.periods, flags=re.IGNORECASE)
        if m:
            periods: Any = -int(re.sub(r"^last\s+", "", parsed.periods, flags=re.IGNORECASE))
        else:
            periods = parsed.periods
    else:
        periods = -6

    return ibge_variables(
        aggregate=int(parsed.aggregate["id"]),
        variable=variable,
        periods=periods,
        localities=localities,
        classification=classification,
        validate=validate,
    )

Utilities

parse_ibge_value

parse_ibge_value(x: Any) -> Any

Coerce an IBGE value column to numeric.

Conversions, following IBGE's tabular presentation standards:

  • "-" (numeric zero, not rounding) -> 0
  • ".." (not applicable), "..." (not available), "X" (suppressed) -> NaN
  • everything else -> :func:pandas.to_numeric

Accepts a scalar, a list, or a :class:pandas.Series and returns the matching shape (Series in, Series out; scalar in, float out).

Source code in src/ibgepy/values.py
def parse_ibge_value(x: Any) -> Any:
    """Coerce an IBGE ``value`` column to numeric.

    Conversions, following IBGE's tabular presentation standards:

    * ``"-"`` (numeric zero, not rounding) -> ``0``
    * ``".."`` (not applicable), ``"..."`` (not available), ``"X"``
      (suppressed) -> ``NaN``
    * everything else -> :func:`pandas.to_numeric`

    Accepts a scalar, a list, or a :class:`pandas.Series` and returns the
    matching shape (Series in, Series out; scalar in, float out).
    """
    scalar_input = not isinstance(x, (pd.Series, list, tuple, np.ndarray))
    series = pd.Series([x] if scalar_input else x)

    if pd.api.types.is_numeric_dtype(series):
        result = series.astype(float)
    else:
        text = series.astype("string")
        result = pd.to_numeric(text, errors="coerce")
        result = result.mask((text == "-").fillna(False), 0.0)
        result = result.mask(text.isin(SPECIAL_NA).fillna(False), np.nan)
        # Normalize to plain float64 (np.nan) rather than nullable Float64 (pd.NA).
        result = result.astype("float64")

    if scalar_input:
        value = result.iloc[0]
        return float(value) if pd.notna(value) else np.nan
    return result.reset_index(drop=True)

ibge_clear_cache

ibge_clear_cache() -> None

Remove all cached metadata (aggregates and surveys).

Forces fresh API calls on subsequent requests. Public alias: :func:ibgepy.ibge_clear_cache.

Source code in src/ibgepy/_cache.py
def clear_cache() -> None:
    """Remove all cached metadata (aggregates and surveys).

    Forces fresh API calls on subsequent requests. Public alias:
    :func:`ibgepy.ibge_clear_cache`.
    """
    _AGG_META_CACHE.clear()
    _SURVEY_CACHE.clear()
    from . import _msg

    _msg.success("Metadata cache cleared.")

set_verbose

set_verbose(verbose: bool) -> None

Enable or disable informational messages (success/step/warn).

Source code in src/ibgepy/_msg.py
def set_verbose(verbose: bool) -> None:
    """Enable or disable informational messages (success/step/warn)."""
    global _VERBOSE
    _VERBOSE = bool(verbose)

Returned objects

IbgeMetadata dataclass

IbgeMetadata(id: Any, name: Any, url: Any, survey: Any, subject: Any, periodicity: Dict[str, Any], territorial_level: Dict[str, List[str]], variables: DataFrame, classifications: DataFrame)

Complete metadata for an IBGE aggregate.

classifications is a DataFrame whose categories column holds, for each row, a nested DataFrame of categories (the equivalent of the R list-column).

IbgeSurveyMetadata dataclass

IbgeSurveyMetadata(status: Any, category: Any, type: Any, area: Any, acronym: Any, start_date: Any, deactivation_date: Any, sidra_url: Any, concla_url: Any, thematic_classifications: DataFrame, occurrences: List[Any])

Institutional/methodological metadata for a survey in a period.

SidraQuery dataclass

SidraQuery(aggregate: Dict[str, Any], variables: DataFrame, periods: str, localities: List[Dict[str, Any]], classifications: List[Dict[str, Any]], ibger_call: str, periodicity: Dict[str, Any])

Parsed SIDRA query, enriched with names from the aggregate metadata.

Exceptions

IbgeError

Bases: RuntimeError

Raised when an IBGE API request fails.

ValidationError

Bases: ValueError

Raised when a parameter does not match the aggregate metadata.