# Brazilian Politics Data API (`elaborate_guide/brasil-politica`) Actor

Official Brazilian politics data in one format: deputies, senators, their expenses and votes, bills, TSE candidates and assets, budget amendments, municipal gazettes and SAPL legislatures. Run as a job or as an HTTP API.

- **URL**: https://apify.com/elaborate_guide/brasil-politica.md
- **Developed by:** [Adriano Henrique](https://apify.com/elaborate_guide) (community)
- **Features:** Limited permissions, Single-tenant, Server interface
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

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

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

## Brazilian Politics Data API

One Apify Actor for official Brazilian politics data. It reads the government's own open-data
APIs and bulk files and returns everything in a single normalized format: federal deputies and
senators, what they spend and how they vote, bills, election candidates and declared assets,
budget amendments, municipal official gazettes, and state and city legislatures that run SAPL.

Run it as a normal job (results go to the dataset) or keep it up as an HTTP API in Standby mode.

### Datasets

| Dataset | What | Official source |
|---|---|---|
| `camara.deputados` | Federal deputies in office | Câmara dos Deputados API v2 |
| `camara.despesas` | Deputies' expense claims (cota parlamentar), with receipt links | Câmara yearly bulk file (`/cotas/Ano-YYYY.csv.zip`) |
| `camara.votacoes` | Plenary votes; per person when filtered by name, party or state | Câmara API v2 |
| `camara.proposicoes` | Bills and other proposals | Câmara API v2 |
| `senado.senadores` | Senators in office | Senado Dados Abertos |
| `senado.despesas` | Senators' expense claims (CEAPS) | Senado administrative open data |
| `senado.votacoes` | Plenary roll-call votes, with each senator's vote | Senado Dados Abertos |
| `tse.candidatos` | Candidates for any office: mayors, councillors, governors, deputies, senators, president | TSE bulk files |
| `tse.bens` | Assets each candidate declared, joined with the candidate's name and office | TSE bulk files |
| `transparencia.emendas` | Parliamentary amendments to the federal budget (who sent money where) | Portal da Transparência (CGU), **needs a free key** |
| `diarios.publicacoes` | Municipal official gazettes: appointments, decrees, contracts | Querido Diário (Open Knowledge Brasil) |
| `sapl.parlamentares` | Councillors or state deputies of any SAPL legislature | SAPL REST API |
| `sapl.materias` | Bills from any SAPL legislature, with author names | SAPL REST API |

### Output format

Every row has the same shape, whatever the source:

```json
{
  "dataset": "camara.despesas",
  "source": "Câmara dos Deputados",
  "level": "federal",
  "kind": "expense",
  "id": "8165015",
  "date": "2026-10-09",
  "title": "MANUTENÇÃO DE ESCRITÓRIO DE APOIO À ATIVIDADE PARLAMENTAR — STARLINK BRAZIL ...",
  "politician": { "id": "204534", "name": "Tabata Amaral", "party": "PSB", "uf": "SP", "role": "Deputado(a) Federal" },
  "amount": 619,
  "url": "https://www.camara.leg.br/cota-parlamentar/documentos/publ/...pdf",
  "details": { "category": "...", "supplier": "...", "supplierDocument": "...", "month": 10, "year": 2026 }
}
```

`level` is `federal`, `estadual` or `municipal`. `kind` is one of `politician`, `expense`, `vote`
(one person's vote), `voting` (a whole voting session), `bill`, `candidate`, `asset`, `amendment` or `gazette`.
Source-specific fields live in `details`.

### Examples

How did a deputy vote in the last 30 days?

```json
{ "datasets": ["camara.votacoes"], "name": "erika hilton" }
```

Everything about one senator: profile, expenses this year, votes.

```json
{ "datasets": ["senado.senadores", "senado.despesas", "senado.votacoes"], "name": "randolfe" }
```

Who won for mayor in Campinas in 2024?

```json
{ "datasets": ["tse.candidatos"], "electionYear": 2024, "uf": ["SP"], "municipality": "campinas", "office": "prefeito", "electedOnly": true }
```

What did the elected governors of Acre and Amapá declare in 2022?

```json
{ "datasets": ["tse.bens"], "electionYear": 2022, "uf": ["AC", "AP"], "office": "governador", "electedOnly": true }
```

Appointments ("nomeia") in São Paulo's municipal gazette this month:

```json
{ "datasets": ["diarios.publicacoes"], "territoryIds": ["3550308"], "keywords": "nomeia", "dateFrom": "2026-10-01" }
```

Latest bills at the Acre state assembly:

```json
{ "datasets": ["sapl.materias"], "saplUrls": ["https://sapl.al.ac.leg.br"] }
```

### HTTP API (Standby mode)

With Standby enabled, the Actor answers GET requests. Every input field is a query parameter;
lists are comma-separated.

```
GET /datasets
GET /?datasets=camara.deputados&uf=SP&party=PSOL&maxItems=20
GET /?datasets=senado.votacoes,camara.votacoes&name=lula&dateFrom=2026-01-01
```

The response is `{ count, counts, errors, items }`. `maxItems` defaults to 50 per dataset here.
In Standby the Transparência key is read from the `TRANSPARENCIA_API_KEY` environment variable, never from the URL.

### Run locally

```bash
npm install
apify run --input '{"datasets":["camara.deputados"],"uf":["SP"]}'
npm run serve:dev   # Standby API on http://localhost:4321
npm test
```

Deploy with `apify push`.

### Notes and limits

- **Partial failure is normal.** Datasets run in parallel and one failing upstream doesn't stop
  the others. Failures are listed in the `SUMMARY` record of the key-value store. The run only
  fails if every dataset fails.
- **Câmara expenses** come from the bulk file because the `/deputados/{id}/despesas` endpoint has
  been returning empty lists. The file is updated daily.
- **TSE files are large** (about 70 MB per election for candidates). Always pass `uf` when you can.
  Downloads are cached within a run, so `tse.candidatos` and `tse.bens` together download the candidate file once.
- **Senado expenses** have no party or state in the feed. They're filled in from the current senators list, so former senators have neither, and the `uf` and `party` filters skip them.
- **Senado vote totals** are counted from the ballots when the feed leaves them empty, except for secret votes, where ballots only say "Votou".
- **Budget amendments** filter by author name through the API. Locations are free text, so filter places with `keywords`.
- **State and city coverage.** City councils and state assemblies are only reachable when they use
  SAPL (add their URL to `saplUrls`) or publish to Querido Diário. Many do, but not all. Other
  legislatures would need their own adapter in `src/sources/`.
- **Privacy (LGPD).** CPFs, voter IDs and e-mails in TSE data are dropped, and only the birth year
  is kept. Supplier CPFs in expense data are masked the way government portals mask them.
  Company CNPJs are kept.

### Adding a source

Write an async generator in `src/sources/` that yields `PoliticalRecord`s (see `src/types.ts`),
add its name to `DATASET_NAMES`, register it in `src/collect.ts`, and add it to the `datasets`
enum in `.actor/input_schema.json`.

# Actor input Schema

## `datasets` (type: `array`):

One or more datasets. They run in parallel and land in the same output, each row tagged with its `dataset`.

## `maxItemsPerDataset` (type: `integer`):

Stops each dataset after this many records.

## `name` (type: `string`):

Part of a name, accents and case ignored, e.g. "tabata" or "Randolfe". With vote datasets, returns how this person voted.

## `politicianId` (type: `string`):

The source's own ID (Câmara deputy id, Senado código parlamentar, TSE SQ_CANDIDATO, SAPL id). Taken from `politician.id` in earlier results.

## `uf` (type: `array`):

Two-letter state codes, e.g. SP, RJ. Strongly recommended for TSE datasets, which otherwise download every state.

## `party` (type: `array`):

Party acronyms, e.g. PT, PL, MDB.

## `keywords` (type: `string`):

Searches bill summaries, vote descriptions, expense categories/suppliers, assets and gazette text.

## `dateFrom` (type: `string`):

YYYY-MM-DD. Used by votes, bills, gazettes and expenses. Default: 30 days ago.

## `dateTo` (type: `string`):

YYYY-MM-DD. Default: today.

## `year` (type: `integer`):

Which year's expenses or amendments to read. Default: current year.

## `month` (type: `integer`):

Optional 1–12.

## `includeVotes` (type: `boolean`):

For vote datasets without a person filter, attach each legislator's vote and a tally to every voting session.

## `electionYear` (type: `integer`):

e.g. 2022 (general) or 2024 (municipal). Default: the most recent election.

## `office` (type: `string`):

Exact office, accents and case ignored, e.g. VEREADOR, PREFEITO, VICE-PREFEITO, GOVERNADOR, DEPUTADO ESTADUAL, DEPUTADO FEDERAL, SENADOR.

## `municipality` (type: `string`):

City name for municipal elections, e.g. CAMPINAS.

## `electedOnly` (type: `boolean`):

Only candidates who won.

## `saplUrls` (type: `array`):

Base URLs of SAPL installs (many câmaras municipais and some assembleias), e.g. https://sapl.al.ac.leg.br

## `territoryIds` (type: `array`):

7-digit IBGE codes, e.g. 3550308 (São Paulo), 3509502 (Campinas). Leave empty to search every covered city.

## `transparenciaApiKey` (type: `string`):

Free key from portaldatransparencia.gov.br/api-de-dados/cadastrar-email. Only needed for budget amendments.

## Actor input object example

```json
{
  "datasets": [
    "camara.deputados",
    "senado.senadores"
  ],
  "maxItemsPerDataset": 200,
  "includeVotes": false,
  "electedOnly": false
}
```

# Actor output Schema

## `records` (type: `string`):

All normalized records from every requested dataset.

## `summary` (type: `string`):

Record count per dataset and any datasets that failed.

# 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 = {
    "datasets": [
        "camara.deputados",
        "senado.senadores"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("elaborate_guide/brasil-politica").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 = { "datasets": [
        "camara.deputados",
        "senado.senadores",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("elaborate_guide/brasil-politica").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 '{
  "datasets": [
    "camara.deputados",
    "senado.senadores"
  ]
}' |
apify call elaborate_guide/brasil-politica --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,elaborate_guide/brasil-politica"
        }
    }
}
```

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/fUa3GMlyueZ4boBN5/builds/ZjoMiqBvCitlYjbl3/openapi.json
