# Brazil Fuel Prices by City (ANP Combustíveis) (`br_data_hub/br-anp-fuel-prices`) Actor

Weekly fuel prices in Brazil from the ANP open data survey (not affiliated with the ANP): average, minimum, maximum, standard deviation and stations surveyed per municipality, with IBGE code and week-over-week changes. Optional price per gas station (company, CNPJ, brand, address).

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

## Pricing

from $0.70 / 1,000 price rows

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 Fuel Prices by City (ANP Combustíveis)

Weekly **gasoline, ethanol, diesel, CNG and LPG prices in Brazil**, built from the open data of the weekly fuel price survey (Levantamento de Preços de Combustíveis, LPC) published by Brazil's oil and fuels agency, the ANP (Agência Nacional do Petróleo, Gás Natural e Biocombustíveis).

You get a **clean weekly series** for each municipality: average, minimum and maximum price, standard deviation and number of stations surveyed. Each row also carries the **IBGE municipality code** and the **change against the previous week and against 4 weeks before**, ready for BI, pricing models, fleet cost control or an AI agent.

Optionally, get the **price at each gas station**: company name, CNPJ, brand (bandeira), address and resale price.

Why not just download the ANP files? They are split into weekly spreadsheets, yearly spreadsheets and monthly or half-year CSVs, with names and layouts that change over time (Latin-1 or UTF-8, title rows, full state names, renamed files). This Actor finds the right files, reads every known layout, joins the IBGE code and computes the changes. If the ANP publishes a layout it does not know, the run fails with a clear message instead of returning wrong numbers.

### Input

| Field | Description |
|---|---|
| `mode` | `municipal` (default): one row per municipality, fuel and week. `stations`: one row per gas station, fuel and week. |
| `municipalities` | Name with state (`"São Paulo/SP"`) or IBGE code (`"3550308"`). Default: São Paulo, Rio de Janeiro and Belo Horizonte. |
| `states` | Two-letter codes, e.g. `["SP", "MG"]`: every surveyed municipality of the state. A row matches if it is in a listed state **or** a listed municipality. Leave both empty for all of Brazil (municipal mode only). |
| `fuels` | `gasoline`, `gasoline_premium`, `ethanol`, `diesel_s10`, `diesel_s500`, `cng`, `lpg`. Empty = all. |
| `weeks` | Latest surveyed weeks to return (default 4). |
| `dateFrom`, `dateTo` | Optional period (YYYY-MM-DD) instead of `weeks`. |
| `maxItems` | Stop after this many rows (0 = no limit). |
| `sourceUrls` | Advanced: direct links to ANP files, only if the ANP renames them. |
| `proxyConfiguration` | Optional. Turn on Apify Proxy (country BR) only if gov.br stops answering from the cloud. |

The default input (3 capitals, all fuels, 4 weeks) returns about 84 rows and runs in well under a minute with 256 MB. All of Brazil in municipal mode (about 13,000 rows for 4 weeks) or a whole state in station mode also fit in 256 MB; give 512 MB for long periods in station mode.

### Output

Municipal mode (`mode: "municipal"`):

```json
{
  "weekStart": "2026-10-18",
  "weekEnd": "2026-10-24",
  "state": "SP",
  "municipality": "São Paulo",
  "ibgeCode": "3550308",
  "fuel": "gasoline",
  "fuelName": "Gasolina comum",
  "product": "GASOLINA COMUM",
  "unit": "R$/l",
  "stationsSurveyed": 120,
  "avgPrice": 6.19,
  "minPrice": 5.88,
  "maxPrice": 6.56,
  "stdDev": 0.08,
  "coefVariation": 0.013,
  "prevWeekPrice": 6.314,
  "changeVsPrevWeekPct": -1.96,
  "price4WeeksAgo": 6.239,
  "changeVs4WeeksPct": -0.79,
  "sourceFile": "resumo_semanal_lpc_2026-10-18_2026-10-24.xlsx"
}
```

Station mode (`mode: "stations"`) adds `collectedAt`, `salePrice`, `purchasePrice`, `companyName`, `cnpj`, `brand`, `street`, `number`, `complement`, `district` and `zip`; the changes compare the same station and fuel week over week. (The values above show the format only.)

Notes:

- Weeks run Sunday to Saturday, as in the ANP survey. Since 2017 most municipalities outside the capitals are surveyed every other week, so `prevWeekPrice` is empty when the municipality was not surveyed the week before.
- Only municipalities in the ANP sample are covered (around 400 to 460 municipalities, changing with the ANP budget).
- `diesel_s500` is the ANP's plain "diesel" (óleo diesel comum). `lpg` is the 13 kg cylinder (R$ per cylinder).
- Station files are published monthly by the ANP, so the latest weeks may only exist in municipal mode.

### How much does it cost?

Pay per event, with no extra usage fees:

- **`price`**: US$ 0.001 per row returned (one municipality × fuel × week, or one station × fuel × week in station mode). Failed runs and empty results are free.

The default run (3 capitals, all fuels, 4 weeks, 84 rows) costs about US$ 0.08. Platform compute is included in that price: a run uses 256 MB and well under a minute.

**$0.001 per price row** (`price` event, pay per event). Charged once per row returned: one municipality, fuel and week (or one station, fuel and week in station mode). Failed runs and empty results are free.

| You get | Free tier | Bronze tier (10% off) | Gold tier (30% off) |
|---|---|---|---|
| 100 price rows | $0.10 | $0.09 | $0.07 |
| 1,000 price rows | $1.00 | $0.90 | $0.70 |
| 10,000 price rows | $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 price rows** 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

- ANP, Levantamento de Preços de Combustíveis: weekly municipal spreadsheets ("últimas semanas pesquisadas" and the historical series by municipality) and the station price history (série histórica de preços de combustíveis e de GLP, CSV), published on gov.br/anp and dados.gov.br as open data.
- IBGE municipality codes: table of the 5,571 municipalities from the IBGE Localidades service, shipped inside the Actor (no IBGE call at run time).

The data is the ANP's: prices are those collected by the ANP's contractor in its weekly sample, with the ANP's own caveats. Station records describe businesses (company name, CNPJ, address). If a company name contains an individual's CPF number, the Actor masks it.

**Disclaimer:** this Actor is an independent tool built on public open data. It is not affiliated with, endorsed by or sponsored by the ANP or the IBGE.

This Actor does one thing: ANP fuel prices. Other Brazilian public data (CNPJ, procurement) is in separate Actors from the same publisher.

### More questions

#### How current are the prices?

The ANP surveys prices every week (Sunday to Saturday) and publishes a municipal summary for each surveyed week. Each run downloads the files again, so with the default `weeks: 4` you get the four latest surveyed weeks; `weekStart` and `weekEnd` say which week each row is. Station-level files are published monthly, so the latest weeks may exist only in municipal mode.

#### Why is my city missing, or why are some weeks empty?

The ANP surveys a sample of about 400 to 460 municipalities, not all 5,571. Since 2017 most municipalities outside the capitals are surveyed every other week, so a week can be missing and `prevWeekPrice` can be empty.

#### How do I write the municipality?

By IBGE code (`"3550308"`) or by name with the state: `"São Paulo/SP"`, `"Sao Paulo - SP"` and `"Campinas, SP"` all work, with or without accents. A name alone works when it exists in only one state; otherwise the run fails with a message listing the states to choose from.

#### Can I get prices for every gas station in a state?

Yes, with `"mode": "stations"` and `states`, for example `["MG"]`: one row per station, fuel and week, with company name, CNPJ, brand (bandeira), address, sale price and, when the ANP has it, purchase price. Station mode needs at least one state or municipality, because the national file is very large. Give the run 512 MB for long periods.

#### Which fuels and units are included?

`gasoline` and `gasoline_premium` (comum and aditivada), `ethanol`, `diesel_s10`, `diesel_s500` (the ANP's plain diesel), `cng` (GNV) and `lpg` (the 13 kg LPG cylinder, priced per cylinder). Liquid fuels are priced per liter; the `unit` field of each row carries the unit exactly as the ANP publishes it.

#### How far back can I go?

Use `dateFrom` and `dateTo` for a period, or `weeks` up to 260 (about 5 years). The Actor picks the right ANP files for the period (weekly, yearly and historical spreadsheets, and the monthly or half-year station CSVs) and reads every known layout. If the ANP publishes a layout the Actor does not know, the run fails with a clear message instead of returning wrong numbers.

#### What happens if the ANP renames its files?

The run fails with a clear message instead of returning partial data. You can pass the new links in `sourceUrls` while the Actor is updated.

#### Does it contain personal data?

The station records describe businesses: company name, CNPJ and address, as the ANP publishes them. Some individual entrepreneurs have their CPF in the company name; the Actor masks it.

### 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-anp-fuel-prices/run-sync-get-dataset-items?token=<YOUR_API_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"municipalities": ["São Paulo/SP", "Rio de Janeiro/RJ", "Belo Horizonte/MG"], "proxyConfiguration": {"useApifyProxy": false}}'
```

```python
from apify_client import ApifyClient

client = ApifyClient("<YOUR_API_TOKEN>")
run = client.actor("br_data_hub/br-anp-fuel-prices").call(run_input={'municipalities': ['São Paulo/SP', 'Rio de Janeiro/RJ', 'Belo Horizonte/MG'],
                                      'proxyConfiguration': {'useApifyProxy': False}})
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-anp-fuel-prices` 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?

- ANP, Levantamento de Preços de Combustíveis: weekly municipal spreadsheets ("últimas semanas pesquisadas" and the historical series by municipality) and the station price history (série histórica de preços de combustíveis e de GLP, CSV), published on gov.br/anp and dados.gov.br as open data. - IBGE municipality codes: table of the 5,571 municipalities from the IBGE Localidades service, shipped inside the Actor (no IBGE call at run time).

#### How much does it cost?

$0.001 per price row. 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 row returned: one municipality, fuel and week (or one station, fuel and week in station mode). Failed runs and empty results 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 Exchange Rates API (Cotação PTAX)](https://apify.com/br_data_hub/br-exchange-rates) | Get official PTAX exchange rates from Banco Central do Brasil: buy and sell rates in BRL, parities and bulleti |
| [Brazil Treasury Bonds API (Tesouro Direto)](https://apify.com/br_data_hub/br-tesouro-direto) | Daily rates and unit prices of Brazilian Treasury bonds (Tesouro Direto: Selic, Prefixado, IPCA+, Renda+, Educ |
| [Brazil Inflation Calculator (IPCA, IGP-M, Selic)](https://apify.com/br_data_hub/br-monetary-correction) | Correct BRL amounts in bulk by IPCA, INPC, IGP-M, IGP-DI, IPC-Fipe, Selic, CDI, TR or savings (poupança) using |
| [Brazil Company Financials (CVM DFP/ITR, B3)](https://apify.com/br_data_hub/br-cvm-company-financials) | Standardized financial statements of Brazilian listed companies from CVM open data (DFP annual, ITR quarterly) |
| [Brazil Investment Fund Returns (Fundos CVM)](https://apify.com/br_data_hub/br-cvm-fund-performance) | Ready-made performance metrics for Brazilian investment funds from CVM open data: period, YTD and 12-month ret |

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

### Usar em português

**Preços semanais de combustíveis no Brasil**, a partir dos dados abertos do Levantamento de Preços de Combustíveis (LPC) da ANP: gasolina comum e aditivada, etanol, diesel S10 e S500, GNV e GLP, por município, e opcionalmente por posto.

**Para que serve:** acompanhar o preço do combustível na sua cidade ou região, controlar o custo de frota, montar painéis de BI e modelos de preço, comparar postos e bandeiras, ou dar a um agente de IA o preço médio oficial da semana.

**O que ele resolve:** a ANP publica planilhas semanais, anuais e CSVs mensais ou semestrais, com nomes e formatos que mudam com o tempo. O Actor encontra os arquivos certos, lê todos os formatos conhecidos, junta o código IBGE e calcula as variações. Se a ANP publicar um formato desconhecido, a execução para com mensagem clara em vez de devolver número errado.

**Como usar em 3 passos:**

1. Escolha onde: municípios em `municipalities` ("São Paulo/SP", "Campinas, SP" ou o código IBGE "3550308") e/ou estados em `states` (por exemplo `["SP", "MG"]`). Deixe os dois vazios para o Brasil todo (só no modo municipal).
2. Escolha os combustíveis em `fuels` (`gasoline`, `gasoline_premium`, `ethanol`, `diesel_s10`, `diesel_s500`, `cng`, `lpg`; vazio = todos) e o período: `weeks` (últimas semanas pesquisadas, padrão 4) ou `dateFrom` e `dateTo` (AAAA-MM-DD).
3. Deixe `mode` em `municipal` para uma linha por município, combustível e semana, ou use `stations` para uma linha por posto (exige ao menos um estado ou município). Rode e baixe em JSON, CSV ou Excel.

**Exemplo de entrada:**

```json
{"municipalities": ["Campinas, SP", "3106200"], "fuels": ["gasoline", "ethanol"], "weeks": 8}
```

**Campos principais:** `weekStart` e `weekEnd`, `state`, `municipality`, `ibgeCode`, `fuel` e `fuelName`, `unit` (unidade como a ANP publica, por exemplo R$/l; o GLP é por botijão de 13 kg), `stationsSurveyed` (postos pesquisados), `avgPrice` (preço médio), `minPrice`, `maxPrice`, `stdDev`, `changeVsPrevWeekPct` (variação na semana) e `changeVs4WeeksPct` (contra 4 semanas antes). No modo por posto: `companyName`, `cnpj`, `brand` (bandeira), endereço, `salePrice` e `purchasePrice`.

**Bom saber:**

- A ANP pesquisa uma amostra de cerca de 400 a 460 municípios. Fora das capitais, a maioria é pesquisada semana sim, semana não, então `prevWeekPrice` pode vir vazio.
- Os arquivos por posto saem uma vez por mês: as semanas mais recentes podem existir só no modo municipal.
- CPF que apareça na razão social de empresário individual é mascarado.

**O que é grátis:** execuções com erro e consultas sem resultado. Você paga só por linha entregue (evento `price`). Use `maxItems` ou o custo máximo por execução para limitar o gasto. Fonte: ANP, Levantamento de Preços de Combustíveis (dados abertos); códigos de município do IBGE. Ferramenta independente, sem vínculo com a ANP ou o IBGE.

**Quanto custa:** $0.001 por resultado (`price`); 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-anp-fuel-prices`).

# Actor input Schema

## `municipalities` (type: `array`):

Enter municipalities as name/state ("São Paulo/SP") or 7-digit IBGE code ("3550308"), one per line. A row is returned if it matches a municipality or a state below. Leave both empty for all of Brazil (municipal output only).

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

Enter two-letter state codes, e.g. SP or MG, one per line. Every surveyed municipality of these states is returned.

## `fuels` (type: `array`):

Pick the fuels to return. Leave empty for all. Diesel S500 is ANP's plain "diesel" (comum); LPG is the 13 kg cylinder.

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

Choose "Weekly prices by municipality" for one row per municipality, fuel and week (average, min, max, standard deviation, stations surveyed), or "Price per gas station" for one row per station, fuel and week, with company, CNPJ, brand, address and resale price.

## `weeks` (type: `integer`):

Set how many of the most recent survey weeks to return (ANP weeks run Sunday to Saturday), e.g. 4 for the last month. Ignored when you fill in a date below.

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

Pick the start of the period (YYYY-MM-DD) to use instead of Latest weeks. Weeks that overlap the period are returned.

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

Pick the end of the period (YYYY-MM-DD). Leave empty for today.

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

Set the maximum number of rows to save (each row is one charged price event), e.g. 1000 to cap the cost. 0 means no limit.

## `sourceUrls` (type: `array`):

Paste direct links to ANP spreadsheets (.xlsx, municipal output) or station CSV/ZIP files (station output) only if ANP renamed its files and discovery fails. Leave empty normally.

## `proxyConfiguration` (type: `object`):

Leave off normally. Turn on Apify Proxy with country BR only if gov.br stops answering from the Apify cloud (it may block traffic from outside Brazil).

## Actor input object example

```json
{
  "municipalities": [
    "São Paulo/SP",
    "Rio de Janeiro/RJ",
    "Belo Horizonte/MG"
  ],
  "fuels": [
    "gasoline",
    "ethanol",
    "diesel_s10"
  ],
  "mode": "municipal",
  "weeks": 4,
  "maxItems": 0,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# 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 = {
    "municipalities": [
        "São Paulo/SP",
        "Rio de Janeiro/RJ",
        "Belo Horizonte/MG"
    ],
    "fuels": [
        "gasoline",
        "ethanol",
        "diesel_s10"
    ],
    "proxyConfiguration": {
        "useApifyProxy": false
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("br_data_hub/br-anp-fuel-prices").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 = {
    "municipalities": [
        "São Paulo/SP",
        "Rio de Janeiro/RJ",
        "Belo Horizonte/MG",
    ],
    "fuels": [
        "gasoline",
        "ethanol",
        "diesel_s10",
    ],
    "proxyConfiguration": { "useApifyProxy": False },
}

# Run the Actor and wait for it to finish
run = client.actor("br_data_hub/br-anp-fuel-prices").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 '{
  "municipalities": [
    "São Paulo/SP",
    "Rio de Janeiro/RJ",
    "Belo Horizonte/MG"
  ],
  "fuels": [
    "gasoline",
    "ethanol",
    "diesel_s10"
  ],
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}' |
apify call br_data_hub/br-anp-fuel-prices --silent --output-dataset

```

## MCP server setup

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

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/bzbmhtKesJ0kzIT1u/builds/q2jFiqvi8vNlS25RB/openapi.json
