# Brazil Municipalities & IBGE Codes (Municípios) (`br_data_hub/br-ibge-localities`) Actor

List Brazilian municipalities, search them by name (accents and typos tolerated) or resolve IBGE codes. Returns the official 7-digit IBGE code, state, region and IBGE regional divisions.

- **URL**: https://apify.com/br_data_hub/br-ibge-localities.md
- **Developed by:** [br_data_hub](https://apify.com/br_data_hub) (community)
- **Categories:** AI, Developer tools, Business
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.70 / 1,000 municipalities

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/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
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.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## 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.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Brazil Municipalities & IBGE Codes (Municípios)

Get every **Brazilian municipality** with its **official 7-digit IBGE code**, state, region and the IBGE regional divisions, straight from the official **IBGE localities API**.

Use it to standardize addresses, join datasets that use IBGE codes (DATASUS, Receita Federal, TSE, PNCP), turn messy city names into codes, or give an AI agent a reliable lookup of Brazilian places.

### Three modes

| Mode | What it does | Example input |
|---|---|---|
| `list` | All municipalities of some states (or the whole country), sorted by name | `{"mode": "list", "states": ["SC"]}` |
| `search` | Finds municipalities by name. Accents, case, hyphens and small typos are tolerated | `{"mode": "search", "names": ["sao jose dos campos", "brazilia"]}` |
| `resolve` | Turns IBGE codes into full records. Accepts 7 digits or 6 digits (without check digit, as in DATASUS) | `{"mode": "resolve", "codes": ["3550308", "530010"]}` |

The default input lists the municipalities of the Federal District (DF) and finishes in seconds.

### What you get per municipality

- `ibgeCode` (7 digits) and `ibgeCode6` (6 digits, without check digit)
- `name`, `state` (UF), `stateName`, `stateIbgeCode`
- `region` (Norte, Nordeste, Centro-Oeste, Sudeste, Sul)
- `mesoregion` and `microregion` (older IBGE division) with codes
- `intermediateRegion` and `immediateRegion` (IBGE 2017 division) with codes
- In search mode, `query` and `matchScore` (1 = exact name, ignoring accents and case)

Some municipalities created recently have no meso/microregion in IBGE; these fields come as `null`.

### Input

| Field | Description |
|---|---|
| `mode` | `list`, `search` or `resolve`. |
| `states` | Two-letter state codes, e.g. `["SP", "MG"]`. List mode: only these states; empty = whole country. Search mode: matches in these states come first, and the whole country is searched only when there is none. Resolve mode: ignored (codes are unique). |
| `names` | Search mode: names to look for. |
| `maxResultsPerName` | Search mode: best matches per name (default 3). |
| `codes` | Resolve mode: IBGE codes. |
| `maxItems` | Stop after this many results (default 10,000). |

Names or codes without a match are returned as a row with an `error` field and are not charged.

### Output example

```json
{
  "query": "sao jose dos campos",
  "matchScore": 1,
  "ibgeCode": "3549904",
  "ibgeCode6": "354990",
  "name": "São José dos Campos",
  "state": "SP",
  "stateName": "São Paulo",
  "region": "Sudeste",
  "mesoregion": "Vale do Paraíba Paulista",
  "microregion": "São José dos Campos",
  "intermediateRegion": "São José dos Campos",
  "immediateRegion": "São José dos Campos"
}
```

### How much does it cost?

You pay only for municipalities returned. Names or codes not found are free.

This Actor does one thing: municipalities and IBGE codes. Company data is in **Brazil CNPJ Lookup** and public contracts in **Brazil Public Contracts (PNCP)**, from the same publisher.

**$0.001 per municipality** (`locality` event, pay per event). Charged once per municipality returned. Names and codes not found are free.

- `apify-actor-start`: $0.00005 (Charged once when a run starts (Apify synthetic event).)

| You get | Free tier | Bronze tier (10% off) | Gold tier (30% off) |
|---|---|---|---|
| 100 municipalitys | $0.10 | $0.09 | $0.07 |
| 1,000 municipalitys | $1.00 | $0.90 | $0.70 |
| 10,000 municipalitys | $10.00 | $9.00 | $7.00 |

Discounts follow your Apify subscription tier: Bronze 10%, Silver 20%, Gold and above 30%. No subscription to this Actor and no charge for platform usage: you pay only for results.
The Apify Free plan includes $5 of monthly credit, enough for about **5,000 municipalitys** at the list price.
You can cap the cost of any run with **Maximum cost per run**; the Actor stops when it is reached.

### Data source and limits

Official public API of IBGE (`servicodados.ibge.gov.br/api/v1/localidades`). The Actor ships a snapshot of that API (all 5,571 municipalities), refreshed by the publisher, so runs are fast and do not depend on the IBGE servers. New municipalities are rare (the newest, Boa Esperança do Norte in Mato Grosso, is already included); the snapshot date is in the run log.

### More questions

#### Why 5,571 and not 5,570 municipalities?

The IBGE list includes Boa Esperança do Norte (MT), the newest municipality, and also Brasília (DF) and the state district of Fernando de Noronha (PE), which have IBGE municipality codes although they are not municipalities in the strict legal sense. They are returned like any other record so your joins with IBGE-coded data do not lose rows.

#### How do I get the code of a city whose name repeats in several states?

232 names exist in more than one state (there are 5 municipalities called Bom Jesus). In search mode, add the state in `states` (for example `["PI"]`) and that state's municipality is returned. If the state has no match, the Actor searches the whole country instead of returning nothing, so check the `state` field. Without a state, each name returns its best matches up to **Results per name** (default 3, maximum 50).

#### What does `matchScore` mean?

1 = same name ignoring accents, case and punctuation; 0.9 = the official name starts with your text (`sao paulo` → São Paulo de Olivença); 0.85 = every word you typed starts a word of the name (`sao jose campos`); below that, similarity by spelling distance, which tolerates typos (`brazilia` → Brasília). Matches below 0.75 are discarded, and a name with no match returns a free row with `error`.

#### Does it accept the 6-digit codes used by DATASUS?

Yes. Resolve mode accepts the 7-digit IBGE code (`3550308`) or the 6-digit code without the check digit (`355030`) used by DATASUS/SUS systems, and returns both in `ibgeCode` and `ibgeCode6`.

#### Meso/microregions or intermediate/immediate regions: which should I use?

IBGE replaced the meso and microregions with the intermediate and immediate geographic regions in 2017 and no longer creates the old ones, so municipalities created later (Boa Esperança do Norte) have `mesoregion` and `microregion` as `null`. For new analyses use `intermediateRegion` and `immediateRegion`, which cover every municipality; keep the old ones only to match legacy data.

#### How current is the data?

The Actor reads a snapshot of the official IBGE localities API stored with the code, because the IBGE servers do not answer requests from Apify's cloud. The snapshot date is printed in the run log, and the publisher refreshes it from a machine in Brazil. Municipalities are created very rarely, so a recent snapshot is equivalent to the live API.

#### Can I list the whole country in one run?

Yes: list mode with `states` empty returns all municipalities sorted by name (the input form starts with DF filled in, so remove it, or send `"states": []` through the API), and the default `maxItems` (10,000) already covers them. Since the data is local, a full run finishes in seconds.

### Use it via API

Run it from any language and get the results as JSON. Replace `<YOUR_API_TOKEN>` with your [Apify API token](https://console.apify.com/settings/integrations).

```bash
curl -X POST "https://api.apify.com/v2/acts/br_data_hub~br-ibge-localities/run-sync-get-dataset-items?token=<YOUR_API_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"mode": "list", "states": ["DF"], "maxResultsPerName": 3, "maxItems": 10000}'
```

```python
from apify_client import ApifyClient

client = ApifyClient("<YOUR_API_TOKEN>")
run = client.actor("br_data_hub/br-ibge-localities").call(run_input={'mode': 'list', 'states': ['DF'], 'maxResultsPerName': 3, 'maxItems': 10000})
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)
```

You can also schedule runs, send results to webhooks, or connect the Actor to Make, Zapier, n8n, Google Sheets and other [integrations](https://docs.apify.com/platform/integrations).

### Use it with AI agents (MCP)

This Actor is ready for AI agents: typed input and output schemas, pay-per-event pricing, limited permissions and short runs.

- **Apify MCP server:** add `https://mcp.apify.com/?tools=br_data_hub/br-ibge-localities` to Claude, ChatGPT, Cursor, VS Code or any MCP client, and the agent can call this Actor as a tool.
- **Agent frameworks:** call it from LangChain, LlamaIndex, CrewAI or the OpenAI Agents SDK through the Apify integrations, or with the API call above.
- Results come as structured JSON with stable field names, documented in the **Output** tab.

### FAQ

#### Where does the data come from?

Official public API of IBGE (`servicodados.ibge.gov.br/api/v1/localidades`). The Actor ships a snapshot of that API (all 5,571 municipalities), refreshed by the publisher, so runs are fast and do not depend on the IBGE servers. New municipalities are rare (the newest, Boa Esperança do Norte in Mato Grosso, is already included); the snapshot date is in the run log.

#### How much does it cost?

$0.001 per municipality. Discounts follow your Apify subscription tier: Bronze 10%, Silver 20%, Gold and above 30%. See **How much does it cost?** above for examples.

#### Do I pay for errors or empty results?

No. Charged once per municipality returned. Names and codes not found are free.

#### Can I run it on a schedule or connect it to other tools?

Yes. Use Apify schedules to run it daily or weekly, webhooks to get notified, and integrations such as Make, Zapier, n8n and Google Sheets. Everything also works through the API.

#### Can AI agents use it?

Yes. It works as a tool in the Apify MCP server and in agent frameworks, and AI agents can pay per event. See **Use it with AI agents (MCP)**.

#### Is it legal to use this data?

The Actor reads only public, official sources and keeps personal data masked as the source publishes it. You are responsible for how you use the data, including LGPD compliance.

#### I found a bug or need a feature. What should I do?

Open an issue in the **Issues** tab. We answer within 14 days, usually much sooner.

### More Actors from BR Data Hub

| Actor | What it does |
|---|---|
| [Brazil CNPJ Lookup API (Consulta CNPJ)](https://apify.com/br_data_hub/br-cnpj-lookup) | Look up Brazilian companies by CNPJ: registration status, partners (masked CPF), activities, tax regime and sc |
| [Brazil Public Contracts API (PNCP Contratos)](https://apify.com/br_data_hub/br-pncp-contracts) | Get Brazilian government contracts from PNCP, the official national procurement portal: buyer, supplier, objec |
| [Brazil Open Tenders API (Licitações Abertas)](https://apify.com/br_data_hub/br-pncp-open-tenders) | Find Brazilian government tenders that are open for proposals right now, from PNCP, the official national proc |
| [Brazil Holidays & Business Days (Feriados)](https://apify.com/br_data_hub/br-holidays) | Brazilian national and state holidays for all 27 states, with the law behind each one |
| [Brazil Banks & Pix Directory (Bancos e ISPB)](https://apify.com/br_data_hub/br-bank-pix-directory) | Every Brazilian bank and payment institution from official Banco Central lists: ISPB, COMPE bank code, short a |
| [Brazil Boleto Validator & Parser (Boleto)](https://apify.com/br_data_hub/br-boleto-parser) | Validate Brazilian boletos in bulk (digitable line or barcode, bank and utility/tax slips): check digits per f |

See all our Actors at [apify.com/br_data_hub](https://apify.com/br_data_hub).

### Usar em português

**Municípios brasileiros e códigos IBGE.** Para cada município: código IBGE de 7 dígitos e de 6 dígitos (formato do DATASUS), nome oficial, UF, nome e código da UF, região, região intermediária e imediata (divisão atual do IBGE) e mesorregião e microrregião (divisão antiga, quando existir). Os dados são da API oficial de Localidades do IBGE, numa cópia guardada no Actor e datada no log, porque os servidores do IBGE não respondem à nuvem da Apify.

**Para que serve:** padronizar endereços e cadastros, trocar nomes de cidade escritos de qualquer jeito pelo código IBGE, cruzar bases que usam o código (DATASUS, Receita Federal, TSE, PNCP) e dar a agentes de IA uma consulta confiável de municípios.

**Como usar em 3 passos:**

1. Clique em **Try for free** e escolha o modo: **List municipalities** (listar por UF), **Search by name** (buscar por nome) ou **Resolve IBGE codes** (resolver códigos).
2. Preencha as UFs, os nomes ou os códigos. Na listagem, só as UFs informadas entram (apague o DF que vem preenchido para listar o país inteiro). Na busca, acentos, maiúsculas, hífens e pequenos erros de digitação são tolerados, e a UF dá preferência aos municípios dela para separar cidades com o mesmo nome; se não houver nenhum na UF, a busca vale para o país todo. Na resolução de códigos, a UF é ignorada.
3. Clique em **Start** e baixe na aba **Output** (JSON, CSV, Excel) ou leia pela API.

**Exemplos de entrada:**

```json
{ "mode": "search", "names": ["sao jose dos campos", "brazilia", "bom jesus"], "states": [], "maxResultsPerName": 3 }
```

```json
{ "mode": "resolve", "codes": ["3550308", "530010"] }
```

**Campos principais:** `ibgeCode`, `ibgeCode6`, `name`, `state`, `stateName`, `stateIbgeCode`, `region`, `regionCode`, `intermediateRegion` e `immediateRegion` (com códigos), `mesoregion` e `microregion` (com códigos); na busca, também `query` e `matchScore` (1 = nome idêntico).

**O que é grátis:** nome ou código sem correspondência sai como uma linha com `error` e não é cobrado. Você paga só pelos municípios entregues.

**Quanto custa:** $0.001 por resultado (`locality`); 1.000 resultados saem por $1.00. Desconto pelo nível da assinatura Apify: Bronze 10%, Silver 20%, Gold ou acima 30%. Erros e consultas sem resultado não são cobrados. Use também pela API ou por agentes de IA no servidor MCP da Apify (`https://mcp.apify.com/?tools=br_data_hub/br-ibge-localities`).

# Actor input Schema

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

Choose List to get every municipality (optionally of some states), Search to find municipalities by name, or Resolve to turn IBGE codes into full records.

## `states` (type: `array`):

Enter two-letter state codes, e.g. SP, RJ, DF, one per line. List mode returns only these states; remove every state to list the whole country (5,571 municipalities). Search mode prefers matches in these states and looks in the whole country only when there is none. Resolve mode ignores them (IBGE codes are unique).

## `names` (type: `array`):

Search mode: enter municipality names, one per line, e.g. sao jose dos campos. Accents, case and small typos are tolerated; add states to tell apart cities with the same name.

## `maxResultsPerName` (type: `integer`):

Search mode: set how many best matches to return for each name, e.g. 3.

## `codes` (type: `array`):

Resolve mode: enter 7-digit municipality codes (e.g. 3550308) or 6-digit codes without the check digit, as used by DATASUS (e.g. 355030), one per line.

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

Set the maximum number of municipalities to return, e.g. 100 to cap the cost.

## Actor input object example

```json
{
  "mode": "list",
  "states": [
    "DF"
  ],
  "names": [],
  "maxResultsPerName": 3,
  "codes": [],
  "maxItems": 10000
}
```

# Actor output Schema

## `dataset` (type: `string`):

Dataset with all results

# 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 = {
    "states": [
        "DF"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("br_data_hub/br-ibge-localities").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 = { "states": ["DF"] }

# Run the Actor and wait for it to finish
run = client.actor("br_data_hub/br-ibge-localities").call(run_input=run_input)

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

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

```

## CLI example

```bash
echo '{
  "states": [
    "DF"
  ]
}' |
apify call br_data_hub/br-ibge-localities --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,br_data_hub/br-ibge-localities"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/SDPm7YnaCSCgFTHX0/builds/ghLP8dTGh4AWtx1mS/openapi.json
