# IBGE Brazil Official Statistics Scraper (`parseforge/ibge-brazil-scraper`) Actor

Scrape the Brazilian Institute of Geography and Statistics (IBGE) public APIs. Pull states, municipalities, the full SIDRA aggregate catalogue, single aggregate metadata, and observation data by period, variable and territorial level (N1 country, N2 region, N3 state, N6 municipality).

- **URL**: https://apify.com/parseforge/ibge-brazil-scraper.md
- **Developed by:** [ParseForge](https://apify.com/parseforge) (community)
- **Categories:** Business, Education, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, NaN bookmarks
- **User rating**: No ratings yet

## Pricing

from $28.12 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

![ParseForge Banner](https://github.com/ParseForge/apify-assets/blob/main/banners/banner-default.jpg?raw=true)

## 📊 IBGE Brazil Statistics Scraper

> 🚀 **Export the official Brazilian statistical catalogue in seconds.** Pull **27 states, 5,500+ municipalities, the full SIDRA aggregate catalogue**, observation data, available periods, and aggregate metadata across the entire IBGE catalogue. No sign-up needed.

> 🕒 **Last updated:** 2026-05-15 · **📊 22 fields** per record · **📦 4,000+ SIDRA aggregates** · **🇧🇷 5,500+ municipalities · 27 states · 5 regions**

The **IBGE Brazil Statistics Scraper** taps the official Brazilian Institute of Geography and Statistics catalogue and returns clean, structured records covering the full SIDRA aggregate library plus the official territorial reference (states, municipalities, regions, mesoregions, microregions). Pull aggregate names, subjects, frequencies, variables, units, periods, and observation values keyed by territorial level (N1 country, N2 region, N3 state, N6 municipality, N7 mesoregion).

Coverage spans every Brazilian municipality (5,500+), every state and federal district, IBGE administrative regions, and **4,000+ SIDRA aggregates** including IPCA inflation, PNAD employment, GDP, demographic census, agricultural surveys, industrial production, foreign trade, and tourism. This Actor turns the territorial reference, full aggregate catalogue, single-aggregate metadata, available periods, and observation data into downloadable CSV, Excel, JSON, or XML in minutes.

| 🎯 Target Audience | 💡 Primary Use Cases |
|---|---|
| Economists, journalists, banking & insurance teams, real estate analysts, researchers, BI engineers, civic-tech developers, NGOs | Inflation tracking, municipal demographic dashboards, agribusiness research, ML feature engineering, Power BI / Tableau feeds, newsroom charts, public-health research |

---

### 📋 What the IBGE Brazil Scraper does

Five workflows in a single Actor:

- 🗺️ **Localidades mode.** Pull the official IBGE territorial reference: 27 states, 5,500+ municipalities, 5 regions, mesoregions, or microregions. Each record includes the IBGE numeric ID, padded ID string, sigla, name, region nesting, and a deep link to the official cidades-e-estados page.
- 📚 **Aggregados mode.** List every SIDRA aggregate with name, subject, and source URL — or pass a single aggregate ID to pull its full metadata block (variables, classifications, territorial levels, frequency).
- 📈 **Data mode.** Pull observation values for one or many aggregates by period, variable, and territorial level. Each row carries the variable label, unit, locality, and period.
- 🧾 **Metadata mode.** Get the variable + unit list for one aggregate or batch up to 100 aggregates in a single run.
- 📅 **Periods mode.** List every available period for one or many aggregates with last-modified timestamps.

Every record carries the official SIDRA deep link (`sidra.ibge.gov.br/tabela/{id}`), so you can verify any number against the source page in one click.

> 💡 **Why it matters:** Brazilian official statistics underpin lending decisions, agribusiness analytics, public-health research, real-estate underwriting, and journalism. Building your own pipeline against the SIDRA catalogue means handling territorial codes, classification cross-products, and Portuguese-only labels by hand. This Actor skips all of that and keeps your dataset fresh on every run.

---

### 🎬 Full Demo

_🚧 Coming soon: a 3-minute walkthrough showing how to go from sign-up to a downloaded dataset._

---

### ⚙️ Input

<table>
<thead>
<tr><th>Input</th><th>Type</th><th>Default</th><th>Behavior</th></tr>
</thead>
<tbody>
<tr><td><code>mode</code></td><td>enum</td><td><code>"aggregados"</code></td><td>One of <code>localidades</code>, <code>aggregados</code>, <code>data</code>, <code>metadata</code>, <code>periods</code>.</td></tr>
<tr><td><code>localidadesType</code></td><td>enum</td><td><code>"estados"</code></td><td>One of <code>estados</code>, <code>municipios</code>, <code>regioes</code>, <code>mesorregioes</code>, <code>microrregioes</code>.</td></tr>
<tr><td><code>aggregateId</code></td><td>string</td><td><code>""</code></td><td>SIDRA aggregate ID (e.g. <code>1685</code>). Required for data mode.</td></tr>
<tr><td><code>aggregateIds</code></td><td>array</td><td><code>[]</code></td><td>Batch lookup for data, metadata, periods modes. Up to 100 IDs per run.</td></tr>
<tr><td><code>period</code></td><td>string</td><td><code>"all"</code></td><td>Period code for data mode (e.g. <code>2021</code>, <code>"202101"</code>, or <code>"all"</code>).</td></tr>
<tr><td><code>variable</code></td><td>string</td><td><code>"allxp"</code></td><td>Variable ID for data mode. <code>"allxp"</code> = all variables.</td></tr>
<tr><td><code>level</code></td><td>enum</td><td><code>"N3"</code></td><td>Territorial level: <code>N1</code> Brazil, <code>N2</code> Region, <code>N3</code> State, <code>N6</code> Municipality, <code>N7</code> Mesoregion.</td></tr>
<tr><td><code>maxItems</code></td><td>integer</td><td><code>10</code></td><td>Records to return. Free plan caps at 10, paid plan at 1,000,000.</td></tr>
</tbody>
</table>

**Example: full list of 27 Brazilian states.**

```json
{
    "mode": "localidades",
    "localidadesType": "estados",
    "maxItems": 30
}
````

**Example: latest IPCA inflation (aggregate 1419) by state for 2026-04.**

```json
{
    "mode": "data",
    "aggregateId": "1419",
    "period": "202604",
    "variable": "63",
    "level": "N3",
    "maxItems": 30
}
```

> ⚠️ **Good to Know:** SIDRA aggregate IDs are integers (e.g. `1419` = IPCA inflation, `1685` = municipal GDP). Use `aggregados` mode first to discover IDs, then `metadata` mode to learn the variables and classifications, then `data` mode to pull observations. Territorial levels: `N1` = Brazil (1 row), `N2` = 5 regions, `N3` = 27 states, `N6` = 5,500+ municipalities.

***

### 📊 Output

Each record contains up to **22 fields** depending on mode. Download the dataset as CSV, Excel, JSON, or XML.

#### 🧾 Schema

| Field | Type | Example |
|---|---|---|
| 🆔 `id` | integer | `35` |
| 🆔 `idString` | string | `"0000035"` |
| 🔗 `url` | string | `"https://www.ibge.gov.br/cidades-e-estados/sp.html"` |
| 🏷️ `sigla` | string | `"SP"` |
| 📛 `nome` | string | `"São Paulo"` |
| 🌎 `regiao` | object | `{ "id": 3, "sigla": "SE", "nome": "Sudeste" }` |
| 🏛️ `microrregiao` | object | `{ "id": 35001, "nome": "Jales" }` |
| 🏛️ `mesorregiao` | object | `{ "id": 3501, "nome": "São José do Rio Preto" }` |
| 🆔 `aggregateId` | integer | `1419` |
| 📛 `aggregateName` | string | `"IPCA - Variação mensal, acumulada no ano..."` |
| 🆔 `variavelId` | integer | `63` |
| 📛 `variavel` | string | `"IPCA - Variação mensal"` |
| 📐 `unidade` | string | `"%"` |
| 🗺️ `localidadeId` | string | `"35"` |
| 🗺️ `localidadeNome` | string | `"São Paulo"` |
| 🆔 `nivelId` | string | `"N3"` |
| 📛 `nivelNome` | string | `"Unidade da Federação"` |
| 📅 `periodo` | string | `"202604"` |
| 💰 `valor` | number | `0.61` |
| 📝 `valorRaw` | string | `"0.61"` |
| 🏷️ `classificacoes` | array | `[{ "id": 315, "nome": "Geral", "categoria": { "7169": "Índice geral" } }]` |
| 🕒 `scrapedAt` | ISO 8601 | `"2026-05-15T10:00:00.000Z"` |

#### 📦 Sample record (localidades mode, estados)

<details>
<summary><strong>🗺️ State of São Paulo (id 35)</strong></summary>

```json
{
    "id": 35,
    "idString": "0000035",
    "url": "https://www.ibge.gov.br/cidades-e-estados/sp.html",
    "sigla": "SP",
    "nome": "São Paulo",
    "regiao": { "id": 3, "sigla": "SE", "nome": "Sudeste" },
    "scrapedAt": "2026-05-15T10:00:00.000Z"
}
```

</details>

<details>
<summary><strong>📈 Data mode: IPCA monthly inflation by state (April 2026)</strong></summary>

```json
{
    "aggregateId": 1419,
    "idString": "0001419",
    "url": "https://sidra.ibge.gov.br/tabela/1419",
    "variavelId": 63,
    "variavel": "IPCA - Variação mensal",
    "unidade": "%",
    "localidadeId": "35",
    "localidadeNome": "São Paulo",
    "nivelId": "N3",
    "nivelNome": "Unidade da Federação",
    "periodo": "202604",
    "valor": 0.61,
    "valorRaw": "0.61",
    "classificacoes": [
        { "id": 315, "nome": "Geral", "categoria": { "7169": "Índice geral" } }
    ],
    "scrapedAt": "2026-05-15T10:00:00.000Z"
}
```

</details>

***

### ✨ Why choose this Actor

| | Capability |
|---|---|
| 🇧🇷 | **Full Brazilian coverage.** 5,500+ municipalities, 27 states, 5 regions, plus mesoregions and microregions. |
| 📚 | **4,000+ SIDRA aggregates.** IPCA, PNAD, GDP, agricultural surveys, industrial production, demographic census, and more. |
| 🧾 | **Batch metadata.** Up to 100 aggregates' variables, units, and periods in a single run. |
| 📈 | **Multi-level data.** Pull observations at country, region, state, municipality, or mesoregion granularity. |
| 🔁 | **Always fresh.** Every run reflects the current state of the official catalogue. |
| 🧰 | **No setup.** No sign-up, no key, no scraping CSS selectors. |
| 🔗 | **Source-anchored.** Every record carries the official SIDRA or cidades-e-estados deep link. |

> 📊 IBGE is the most-cited reference for Brazilian inflation, employment, GDP, demographic census, and agricultural data. This Actor makes it queryable in seconds.

***

### 📈 How it compares to alternatives

| Approach | Cost | Coverage | Refresh | Filters | Setup |
|---|---|---|---|---|---|
| **⭐ IBGE Brazil Scraper** *(this Actor)* | $5 free credit, then pay-per-use | **5,500+ municipios, 4,000+ aggregates** | **Live per run** | localidades, aggregados, data, metadata, periods | ⚡ 2 min |
| Manual SIDRA downloads | Free | Per-aggregate only | Manual | None | 🐢 Hours per aggregate |
| Macro-data terminals | $24,000+/year | Curated subset | Live | Many | ⏳ Days |
| Build your own pipeline | Engineering hours | What you build | What you build | What you build | 🕒 Weeks |

Pick this Actor when you want broad Brazilian coverage, multi-level granularity, and no parser maintenance.

***

### 🚀 How to use

1. 📝 **Sign up.** [Create a free account with $5 credit](https://console.apify.com/sign-up?fpr=vmoqkp) (takes 2 minutes).
2. 🌐 **Open the Actor.** Go to the IBGE Brazil Statistics Scraper page on the Apify Store.
3. 🎯 **Set input.** Pick a mode (start with `aggregados` to browse the catalogue), set `maxItems`, and click Start.
4. 🚀 **Run it.** Click **Start** and let the Actor collect your data.
5. 📥 **Download.** Grab your results in the **Dataset** tab as CSV, Excel, JSON, or XML.

> ⏱️ Total time from signup to downloaded dataset: **3-5 minutes.** No coding required.

***

### 💼 Business use cases

<table>
<tr>
<td width="50%" valign="top">

#### 🏦 Banking, fintech, and insurance

- Live IPCA inflation feeds for retail-rate dashboards in Brazil
- Mortgage and insurance underwriting fed by PNAD employment data
- Macro-forecasting models with quarterly GDP estimates
- Risk dashboards aligned with IBGE official numbers

</td>
<td width="50%" valign="top">

#### 🏘️ PropTech and real estate

- Municipal demographic and household projections for site selection
- State-level wage and employment data for valuation models
- Construction output and housing-starts indicators
- Demographic shifts feeding tenant-targeting

</td>
</tr>
<tr>
<td width="50%" valign="top">

#### 🌾 Agribusiness and commodities

- Municipal agricultural production by crop and livestock
- Seasonal harvest tracking by state and region
- Industrial production and producer-price indicators
- Trade and export data for commodity desks

</td>
<td width="50%" valign="top">

#### 📰 Journalism and policy

- Live charts of inflation, jobs, and GDP for newsrooms
- Municipal explainers backed by census data
- Public-policy briefs with cited, versioned numbers
- Investigative reporting on health, security, and demographics

</td>
</tr>
</table>

***

### 🔌 Automating IBGE Brazil Scraper

Control the scraper programmatically for scheduled runs and pipeline integrations:

- 🟢 **Node.js.** Install the `apify-client` NPM package.
- 🐍 **Python.** Use the `apify-client` PyPI package.
- 📚 See the [Apify API documentation](https://docs.apify.com/api/v2) for full details.

The [Apify Schedules feature](https://docs.apify.com/platform/schedules) lets you trigger this Actor on any cron interval. Daily refreshes for high-frequency aggregates (IPCA, PNAD, industrial production) keep dashboards current with no engineering effort.

***

### 🌟 Beyond business use cases

Data like this powers more than commercial workflows. The same structured records support research, education, civic projects, and personal initiatives.

<table>
<tr>
<td width="50%">

#### 🎓 Research and academia

- Macroeconomic theses with cited, versioned data pulls
- Public-health and demographic research at the municipal level
- Reproducible studies with stable SIDRA aggregate IDs
- Open-data exercises in econometrics and stats courses

</td>
<td width="50%">

#### 🎨 Personal and creative

- Side projects, indie data dashboards, and portfolio demos
- Interactive Brazil maps, inflation trackers, and visualizations
- Content research for data journalists and creators
- Hobbyist time-series for forecasters and analysts

</td>
</tr>
<tr>
<td width="50%">

#### 🤝 Non-profit and civic

- Equity research on regional income, housing, and labour outcomes
- Civic transparency on public spending and services
- Investigative journalism backed by IBGE official numbers
- Open data community contributions and visualizations

</td>
<td width="50%">

#### 🧪 Experimentation

- Train forecasting and anomaly-detection ML models
- Validate macro hypotheses with real time-series
- Prototype agent pipelines that resolve aggregate IDs
- Test BI dashboard concepts with live Brazilian data

</td>
</tr>
</table>

***

### 🤖 Ask an AI assistant about this scraper

Open a ready-to-send prompt about this ParseForge actor in the AI of your choice:

- 💬 [**ChatGPT**](https://chat.openai.com/?q=How%20do%20I%20use%20the%20IBGE%20Brazil%20Statistics%20Scraper%20by%20ParseForge%20on%20Apify%3F%20Show%20me%20input%20examples%2C%20output%20fields%2C%20common%20use%20cases%2C%20and%20how%20to%20integrate%20it%20into%20a%20workflow.)
- 🧠 [**Claude**](https://claude.ai/new?q=How%20do%20I%20use%20the%20IBGE%20Brazil%20Statistics%20Scraper%20by%20ParseForge%20on%20Apify%3F%20Show%20me%20input%20examples%2C%20output%20fields%2C%20common%20use%20cases%2C%20and%20how%20to%20integrate%20it%20into%20a%20workflow.)
- 🔍 [**Perplexity**](https://perplexity.ai/search?q=How%20do%20I%20use%20the%20IBGE%20Brazil%20Statistics%20Scraper%20by%20ParseForge%20on%20Apify%3F%20Show%20me%20input%20examples%2C%20output%20fields%2C%20common%20use%20cases%2C%20and%20how%20to%20integrate%20it%20into%20a%20workflow.)
- 🅒 [**Copilot**](https://copilot.microsoft.com/?q=How%20do%20I%20use%20the%20IBGE%20Brazil%20Statistics%20Scraper%20by%20ParseForge%20on%20Apify%3F%20Show%20me%20input%20examples%2C%20output%20fields%2C%20common%20use%20cases%2C%20and%20how%20to%20integrate%20it%20into%20a%20workflow.)

***

### ❓ Frequently Asked Questions

#### 🧩 How does it work?

Pick a mode (localidades, aggregados, data, metadata, periods), set the SIDRA aggregate ID or locality type, and click Start. The Actor pulls clean structured records straight from the official IBGE catalogue. No browser automation, no captchas, no setup.

#### 📏 How accurate is the data?

Every value comes directly from the official IBGE catalogue, the canonical source for Brazilian official statistics. No transformation is applied beyond field-name normalization and ISO timestamp stamping.

#### 🔁 How often is the catalogue refreshed?

The catalogue is updated continuously as IBGE releases new aggregates and revises existing ones. Every run of this Actor returns the live state of the catalogue.

#### 🗺️ How do I pull municipal-level data?

Set `level` to `N6` (Municipality) in `data` mode. With 5,500+ Brazilian municipalities, raise `maxItems` accordingly. Use `localidades` mode with `localidadesType: "municipios"` to first pull the full municipality reference and resolve IBGE codes.

#### ⏰ Can I schedule regular runs?

Yes. Use Apify Schedules to run this Actor on any cron interval (hourly, daily, weekly) and keep your downstream database in sync with new IBGE releases.

#### ⚖️ Is this data legal to use?

IBGE publishes its data under terms that permit free reuse with attribution to IBGE. Review the licence terms for your specific use case.

#### 💼 Can I use this data commercially?

Yes. The underlying IBGE data is open and permits commercial use with attribution. You are responsible for complying with the licence and with any downstream regulatory requirements.

#### 💳 Do I need a paid Apify plan to use this Actor?

No. The free Apify plan is enough for testing and small runs (10 records per run). A paid plan lifts the limit and gives you access to scheduling, higher concurrency, and larger datasets.

#### 🔁 What happens if a run fails or gets interrupted?

Apify automatically retries transient errors. If a run still fails, you can inspect the log in the Runs tab, fix the input, and re-run. Partial datasets from failed runs are preserved so you never lose progress.

#### 🔢 How do I find SIDRA aggregate IDs?

Use `aggregados` mode with no `aggregateId` to list every published SIDRA aggregate. Each record has the integer ID, name, and subject. Common examples: `1419` = IPCA monthly inflation, `1685` = municipal GDP, `4093` = PNAD employment.

#### 🆘 What if I need help?

Our support team is here to help. Contact us through the Apify platform or use the Tally form linked below.

***

### 🔌 Integrate with any app

IBGE Brazil Scraper connects to any cloud service via [Apify integrations](https://apify.com/integrations):

- [**Make**](https://docs.apify.com/platform/integrations/make) - Automate multi-step workflows
- [**Zapier**](https://docs.apify.com/platform/integrations/zapier) - Connect with 5,000+ apps
- [**Slack**](https://docs.apify.com/platform/integrations/slack) - Get run notifications in your channels
- [**Airbyte**](https://docs.apify.com/platform/integrations/airbyte) - Pipe IBGE records into your warehouse
- [**n8n**](https://n8n.io) - Self-hosted workflow automation
- [**Pipedream**](https://pipedream.com) - Event-driven serverless workflows
- [**GitHub**](https://docs.apify.com/platform/integrations/github) - Trigger runs from commits and releases
- [**Google Drive**](https://docs.apify.com/platform/integrations/drive) - Export datasets straight to Sheets

You can also use webhooks to trigger downstream actions when a run finishes. Push fresh IPCA or PNAD numbers into your product backend, or alert your team in Slack the minute a new release lands.

***

### 🔗 Recommended Actors

- [**📊 INE Spain Scraper**](https://apify.com/parseforge/ine-spain-scraper) - Spanish National Statistics Institute
- [**📊 INE Portugal Scraper**](https://apify.com/parseforge/ine-portugal-scraper) - Statistics Portugal indicators
- [**📊 ONS UK Statistics Scraper**](https://apify.com/parseforge/ons-uk-scraper) - UK Office for National Statistics datasets
- [**📊 Statistics Canada Scraper**](https://apify.com/parseforge/statistics-canada-scraper) - Canadian official statistics catalogue
- [**📈 Indexmundi Scraper**](https://apify.com/parseforge/indexmundi-scraper) - Global demographic and economic indicators

> 💡 **Pro Tip:** browse the complete [ParseForge collection](https://apify.com/parseforge) for more reference-data scrapers.

***

**🆘 Need Help?** [**Open our contact form**](https://tally.so/r/BzdKgA) to request a new scraper, propose a custom data project, or report an issue.

***

> **⚠️ Disclaimer:** this Actor is an independent tool and is not affiliated with, endorsed by, or sponsored by the Instituto Brasileiro de Geografia e Estatística or the Government of Brazil. All trademarks mentioned are the property of their respective owners. Only publicly available open data is collected.

# Actor input Schema

## `mode` (type: `string`):

What to scrape from the official IBGE catalogue.

## `localidadesType` (type: `string`):

Which locality level to fetch in localidades mode.

## `aggregateId` (type: `string`):

SIDRA aggregate ID (e.g. 1685). If set in 'aggregados' mode, returns single aggregate metadata. Required for 'data' mode.

## `aggregateIds` (type: `array`):

Array of SIDRA aggregate IDs to fetch in one run (data, metadata, periods modes). Takes precedence over single aggregateId. Max 100 per run.

## `period` (type: `string`):

Period code for data mode (e.g. 2021, '202101'). Use 'all' to fetch all available periods.

## `variable` (type: `string`):

Variable ID for data mode. Use 'allxp' for all variables.

## `level` (type: `string`):

Geographic level for data mode. N1=Brazil, N2=region, N3=state, N6=municipality, N7=mesoregion.

## `maxItems` (type: `integer`):

Free users: Limited to 10 items (preview). Paid users: Optional, max 1,000,000

## Actor input object example

```json
{
  "mode": "aggregados",
  "localidadesType": "estados",
  "aggregateIds": [],
  "period": "all",
  "variable": "allxp",
  "level": "N3",
  "maxItems": 10
}
```

# Actor output Schema

## `overview` (type: `string`):

Overview of scraped data

## `fullData` (type: `string`):

Complete dataset

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "mode": "aggregados",
    "localidadesType": "estados",
    "period": "all",
    "variable": "allxp",
    "level": "N3",
    "maxItems": 10
};

// Run the Actor and wait for it to finish
const run = await client.actor("parseforge/ibge-brazil-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "mode": "aggregados",
    "localidadesType": "estados",
    "period": "all",
    "variable": "allxp",
    "level": "N3",
    "maxItems": 10,
}

# Run the Actor and wait for it to finish
run = client.actor("parseforge/ibge-brazil-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "mode": "aggregados",
  "localidadesType": "estados",
  "period": "all",
  "variable": "allxp",
  "level": "N3",
  "maxItems": 10
}' |
apify call parseforge/ibge-brazil-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=parseforge/ibge-brazil-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "IBGE Brazil Official Statistics Scraper",
        "description": "Scrape the Brazilian Institute of Geography and Statistics (IBGE) public APIs. Pull states, municipalities, the full SIDRA aggregate catalogue, single aggregate metadata, and observation data by period, variable and territorial level (N1 country, N2 region, N3 state, N6 municipality).",
        "version": "0.0",
        "x-build-id": "yiVgfrgymHbxxOu3a"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/parseforge~ibge-brazil-scraper/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-parseforge-ibge-brazil-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/parseforge~ibge-brazil-scraper/runs": {
            "post": {
                "operationId": "runs-sync-parseforge-ibge-brazil-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/parseforge~ibge-brazil-scraper/run-sync": {
            "post": {
                "operationId": "run-sync-parseforge-ibge-brazil-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "properties": {
                    "mode": {
                        "title": "Mode",
                        "enum": [
                            "localidades",
                            "aggregados",
                            "data",
                            "metadata",
                            "periods"
                        ],
                        "type": "string",
                        "description": "What to scrape from the official IBGE catalogue.",
                        "default": "aggregados"
                    },
                    "localidadesType": {
                        "title": "Locality type",
                        "enum": [
                            "estados",
                            "municipios",
                            "regioes",
                            "mesorregioes",
                            "microrregioes"
                        ],
                        "type": "string",
                        "description": "Which locality level to fetch in localidades mode.",
                        "default": "estados"
                    },
                    "aggregateId": {
                        "title": "Aggregate ID",
                        "type": "string",
                        "description": "SIDRA aggregate ID (e.g. 1685). If set in 'aggregados' mode, returns single aggregate metadata. Required for 'data' mode."
                    },
                    "aggregateIds": {
                        "title": "Aggregate IDs (batch lookup)",
                        "type": "array",
                        "description": "Array of SIDRA aggregate IDs to fetch in one run (data, metadata, periods modes). Takes precedence over single aggregateId. Max 100 per run.",
                        "default": [],
                        "items": {
                            "type": "string"
                        }
                    },
                    "period": {
                        "title": "Period",
                        "type": "string",
                        "description": "Period code for data mode (e.g. 2021, '202101'). Use 'all' to fetch all available periods.",
                        "default": "all"
                    },
                    "variable": {
                        "title": "Variable",
                        "type": "string",
                        "description": "Variable ID for data mode. Use 'allxp' for all variables.",
                        "default": "allxp"
                    },
                    "level": {
                        "title": "Territorial level",
                        "enum": [
                            "N1",
                            "N2",
                            "N3",
                            "N6",
                            "N7"
                        ],
                        "type": "string",
                        "description": "Geographic level for data mode. N1=Brazil, N2=region, N3=state, N6=municipality, N7=mesoregion.",
                        "default": "N3"
                    },
                    "maxItems": {
                        "title": "Max Items",
                        "minimum": 1,
                        "maximum": 1000000,
                        "type": "integer",
                        "description": "Free users: Limited to 10 items (preview). Paid users: Optional, max 1,000,000"
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
