# Mexico Gas Prices API - CNE (Regular, Premium, Diesel) (`timekast/mexico-gas-prices-cne`) Actor

Current gasoline and diesel prices for ~13,800 gas stations in Mexico from the official CNE (ex-CRE) feed. Radius search, cheapest-first sort, GPS.

- **URL**: https://apify.com/timekast/mexico-gas-prices-cne.md
- **Developed by:** [TimeKast](https://apify.com/timekast) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 station prices

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

## Mexico Gas Prices API - Official CNE Feed (Regular, Premium, Diesel)

**Current gasoline and diesel prices for ~13,800 gas stations in Mexico**, straight from the energy regulator's official open-data feed (CNE - Comisión Nacional de Energía, formerly CRE). Search around any point, sort by the cheapest fuel, export to JSON/CSV/Excel or use it from the API. No login, no browser: **US$2.00 per 1,000 stations**, and you pay only for stations delivered.

[🇲🇽 Versión en español abajo](#-español)

### What data do you get?

One row per gas station:

- **Prices in MXN per litre** for **regular (Magna)**, **premium** and **diesel**, as currently reported by the permit holder
- Regulator **permit number** (`PL/…/EXP/ES/…`) and **permit-holder name**
- **Latitude / longitude**, plus **distance** in km to your point
- `suspectPrices`: obvious feed typos (e.g. `0.01` MXN) are moved out of the price fields and flagged, so they never pollute your averages
- Source attribution and fetch timestamp

### Use cases

- **Fleets & logistics** - cheapest diesel near depots or along routes.
- **Fuel retailers** - competitor price monitoring within X km of your stations.
- **Analysts & media** - national or regional price distributions and daily snapshots.
- **Apps & AI agents** - "cheapest premium near me" via the Apify API or MCP server.
- **Scheduled monitoring** - run daily with Apify Schedules and push to Google Sheets, a webhook or your database.

### How to use it

1. Set a point (latitude, longitude) and a radius in km - or remove the point to get the whole country.
2. Choose fuels (regular, premium, diesel) and optionally filter by permit-holder name (e.g. `OXXO GAS`, `G500`, `PETRO 7`).
3. Sort by distance or by the cheapest fuel, set **Max stations**, and run.

#### Input example

```json
{
  "near": { "latitude": 19.4326, "longitude": -99.1332, "radiusKm": 5 },
  "fuelTypes": ["regular", "diesel"],
  "sortBy": "distance",
  "maxItems": 500
}
```

| Field | Description |
|---|---|
| `near` | `{ latitude, longitude, radiusKm }`. Omit for all stations in Mexico. |
| `fuelTypes` | Any of `regular`, `premium`, `diesel` (default: all three). |
| `requireAllFuels` | Only stations that report every selected fuel. |
| `nameContains` | Permit-holder name contains this text. |
| `sortBy` | `distance` (needs `near`), `regular`, `premium` or `diesel` (cheapest first). |
| `maxItems` | Stop after N stations (0 = no limit). Default 500. |

#### Output sample

```json
{
  "placeId": "13129",
  "name": "OPERADORA DE MINIESTACIONES COMBUSERV SA DE CV",
  "permitId": "PL/10909/EXP/ES/2015",
  "latitude": 19.42713,
  "longitude": -99.1392,
  "regular": 23.99,
  "premium": 28.99,
  "diesel": null,
  "distanceKm": 0.875,
  "suspectPrices": [],
  "source": "Comisión Nacional de Energía (CNE/CRE) - precios vigentes reportados por permisionarios",
  "fetchedAt": "2026-10-19T12:43:26.010Z"
}
```

### How much does it cost?

Pay per event - you pay only for station rows delivered (plus Apify's tiny standard start fee of US$0.00005 per run).

| Event | Price |
|---|---|
| Station price (one station row) | US$0.002 → **US$2.00 per 1,000 stations** |

Real runs (Oct 2026): 5 km around the Zócalo in Mexico City = 97 stations ≈ **US$0.19** in ~4 s. The whole country (~13,800 stations with prices) ≈ **US$27.70** in under 10 s.
Use **Max stations** or **Max cost per run** to cap spending; the Actor stops cleanly at your budget.

### Data quality

- The run **fails loudly** if the regulator feed is empty or changes format - you never pay for a broken "success".
- Prices outside a plausible range (below 10 or above 60 MXN/L) are flagged in `suspectPrices` instead of being returned as prices.
- `RUN_STATS` and `QUALITY_REPORT` are saved in the run's key-value store.

### FAQ

**How current are the prices?** The feed contains the prices currently in force as reported by each permit holder to the regulator; run it whenever you need a fresh snapshot.

**Why does a station have no diesel/premium?** Not every station sells or reports every fuel; missing values are `null`. Use `requireAllFuels` to skip them.

**Why is the name a company, not a brand?** The regulator publishes the **permit holder** (legal entity). Brand names often appear in it (e.g. `OXXO GAS`), so `nameContains` works for most chains.

**Is this legal?** Yes - it uses the regulator's **public open-data feed** without login. The only names are those of businesses holding public permits. Not affiliated with CNE.

**Can I call it from code or an AI agent?** Yes - via the Apify API, JavaScript/Python clients, Make/Zapier/n8n or the Apify MCP server.

**Found a problem?** Open an issue in the Issues tab; we usually reply within 2 business days.

***

### 🇲🇽 Español

## API de precios de gasolina en México - feed oficial CNE (regular, premium, diésel)

**Precios vigentes de gasolina regular (Magna), premium y diésel de ~13,800 estaciones en México**, desde el feed público oficial del regulador (CNE, antes CRE). Búsqueda por radio alrededor de cualquier punto, orden por el combustible más barato y exportación a JSON/CSV/Excel. Sin login: **US$2.00 por cada 1,000 estaciones**, y solo pagas lo que recibes.

#### ¿Qué datos obtienes?

Una fila por estación: precios en MXN por litro (regular, premium, diésel), número de permiso y nombre del permisionario, latitud/longitud, distancia a tu punto y `suspectPrices` (errores evidentes del feed, como 0.01, se marcan y se quitan de los precios).

#### Casos de uso

- Flotillas y logística: diésel más barato cerca de bases o rutas.
- Gasolineros: monitoreo de precios de la competencia en un radio.
- Analistas y medios: distribución de precios nacional o regional, fotos diarias.
- Apps y agentes de IA: "la premium más barata cerca de mí".

#### Cómo usarlo

```json
{ "near": { "latitude": 19.4326, "longitude": -99.1332, "radiusKm": 5 }, "fuelTypes": ["regular", "diesel"], "sortBy": "distance", "maxItems": 500 }
```

Quita `near` para todo el país. `nameContains` filtra por nombre del permisionario (p. ej. `OXXO GAS`).

#### Campos de salida

`placeId`, `name`, `permitId`, `latitude`, `longitude`, `regular`, `premium`, `diesel`, `distanceKm`, `suspectPrices`, `source`, `fetchedAt`.

#### Precio

Pago por evento: **US$0.002 por estación (US$2.00 por 1,000)** más la tarifa estándar de inicio de Apify (US$0.00005). Ejemplo real: 5 km alrededor del Zócalo = 97 estaciones ≈ US$0.19; todo el país ≈ US$27.70.

#### Preguntas frecuentes

**¿Calidad?** Si el feed viene vacío o cambia de formato, la ejecución falla con mensaje claro.
**¿Es legal?** Sí: usa el feed de **datos abiertos** del regulador, sin login; los únicos nombres son de empresas con permisos públicos. Sin afiliación con la CNE.

# Changelog

This Actor's version history is a separate document: https://apify.com/timekast/mexico-gas-prices-cne/changelog.md

# Actor input Schema

## `near` (type: `object`):

Only stations within radiusKm of this point. Remove it (or leave latitude/longitude empty) to get all ~13,800 stations in Mexico. Example: Zócalo CDMX = 19.4326, -99.1332.

## `fuelTypes` (type: `array`):

Fuels to include. Stations that sell none of them are skipped; unselected fuel columns are removed.

## `nameContains` (type: `string`):

Keep stations whose registered permit-holder name contains this text, e.g. OXXO GAS, G500, PETRO 7.

## `requireAllFuels` (type: `boolean`):

Skip stations that do not report every selected fuel.

## `sortBy` (type: `string`):

Distance needs "near". Otherwise sort by the cheapest price of that fuel.

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

Stop after this many stations (0 = no limit, whole country ≈ 13,800). You pay only per station delivered.

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

Not needed normally (the source is public and reachable from Apify). Only if the source blocks the run region, enable Apify Proxy (RESIDENTIAL, country MX).

## Actor input object example

```json
{
  "near": {
    "latitude": 19.4326,
    "longitude": -99.1332,
    "radiusKm": 5
  },
  "fuelTypes": [
    "regular",
    "premium",
    "diesel"
  ],
  "requireAllFuels": false,
  "sortBy": "distance",
  "maxItems": 50,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

## `results` (type: `string`):

All result rows in the default dataset (overview view).

## `runStats` (type: `string`):

Requests, errors and charged events for this run.

## `qualityReport` (type: `string`):

Schema validation and data-quality summary of this run.

# 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 = {
    "near": {
        "latitude": 19.4326,
        "longitude": -99.1332,
        "radiusKm": 5
    },
    "maxItems": 50
};

// Run the Actor and wait for it to finish
const run = await client.actor("timekast/mexico-gas-prices-cne").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 = {
    "near": {
        "latitude": 19.4326,
        "longitude": -99.1332,
        "radiusKm": 5,
    },
    "maxItems": 50,
}

# Run the Actor and wait for it to finish
run = client.actor("timekast/mexico-gas-prices-cne").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 '{
  "near": {
    "latitude": 19.4326,
    "longitude": -99.1332,
    "radiusKm": 5
  },
  "maxItems": 50
}' |
apify call timekast/mexico-gas-prices-cne --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,timekast/mexico-gas-prices-cne"
        }
    }
}
```

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/0JxR6Zfe7Ong00DOV/builds/Dzvvg9gHwF2Ner35I/openapi.json
