# VietFuel API — Documentation

> JSON REST API for Vietnam retail fuel prices from 12 distributors and 63 provinces (Region 1 & Region 2). No API key, CORS enabled, OpenAPI 3.1 spec included. Prices are always integer VND per litre.

This page is plain Markdown with the same content as `/docs`, readable by humans and LLMs alike. Vietnamese version: `/docs.md`. LLM index: `/llms.txt`. Machine-readable spec: `/openapi.json`.

## Quick facts

| Item | Value |
| --- | --- |
| Production base URL | `https://vietfuel-api.tranqui.workers.dev` |
| Local base URL | `http://localhost:8787` (Wrangler) or `http://localhost:3000` (Node/Docker) |
| Versioning | `/api/v1/*` (backward-compatible alias: `/api/*`) |
| Auth | None for `GET` endpoints. Admin endpoints need `Authorization: Bearer <ADMIN_TOKEN>` |
| Format | UTF-8 JSON. Prices are integer VND/litre. Dates are `YYYY-MM-DD` in Vietnam time (UTC+7) |
| Caching | `Cache-Control: public, max-age=<ttl>, stale-while-revalidate=60` plus `X-Cache: HIT \| MISS \| STALE \| BYPASS` |
| Limits | 4 KB max payload. Only `GET`, `HEAD`, `OPTIONS` (admin also allows `POST`) |

## For users

This part is for people who just want to check prices, no coding needed.

### Where to see prices

- **[Live prices](/live)**: comparison of every distributor, a 63-legacy-province lookup (34 post-merger, matching official fuel-industry tariff tables) and a Region 1 / Region 2 chart.
- **[Price history](/history)**: prices recorded over the last 90 days, filterable by product, distributor and date.
- **Terminal**: run `npm run cli` and pick a number from the menu, no commands to remember.

### Reading the price table

| Label | Meaning |
| --- | --- |
| `V1` | Region 1 price — provinces near ports and fuel depots (Hanoi, HCMC, Da Nang…) |
| `V2` | Region 2 price — remote, mountainous or island provinces. At most 2% above Region 1 |
| `Flat` | The distributor publishes one nationwide price, no Region 1 / Region 2 split |
| `—` | The distributor does not sell or list that product |

### FAQ

- **When do prices change?** Usually Thursday at 15:00 under Decree 80/2023/NĐ-CP. The system checks every 15 minutes during that window.
- **Why do distributors show the same price?** Retail ceilings are set by the state, so most distributors list at or below that level.
- **Which zone is my province in?** Search your province on the Live prices page; the `V1` or `V2` badge shows the zone.
- **The price differs from the pump?** The station price is authoritative. Click the distributor name to open its page and report mismatches on GitHub.
- **Is it free?** Yes. No sign-up required.

## Data concepts

- **Region 1 (`region1`)**: price in areas near ports and main depots.
- **Region 2 (`region2`)**: price in remote, mountainous or island areas — at most 2% above Region 1.
- **Flat price (`price`)**: the distributor publishes a single nationwide price (PVOil, COMECO, Saigon Petro). `region1` and `region2` are then `null`.
- **Adjustment cycle**: under Decree 80/2023/NĐ-CP, prices change every Thursday at 15:00 Vietnam time.
- Any price field may be `null` when a source does not list that product.

### `FuelPriceItem` object

| Field | Type | Description |
| --- | --- | --- |
| `name` | string | Product name, e.g. `Xăng E10 RON 95-III` |
| `region1` | number \| null | Region 1 price (VND/litre) |
| `region2` | number \| null | Region 2 price (VND/litre) |
| `price` | number \| null | Flat price when the source has no zones |
| `unit` | string | Always `VND/lít` |

### Error format

Every error uses the same shape with a matching HTTP status (400, 401, 404, 405, 413, 501, 502, 503).

```json
{
  "success": false,
  "error": {
    "code": "PROVINCE_NOT_FOUND",
    "message": "Province \"abc\" not found. Check GET /api/v1/provinces for valid slugs."
  }
}
```

## Endpoints

### GET /api/v1/fuel-prices

Aggregated prices across all sources, grouped by normalized product name. Each product has a `sources` array with every source's own price.

```bash
curl -s https://vietfuel-api.tranqui.workers.dev/api/v1/fuel-prices
```

```json
{
  "success": true,
  "status": "ok",
  "meta": {
    "primarySourceId": "petrolimex",
    "primarySource": "Petrolimex",
    "sourceCount": 12,
    "priceDate": "2026-12-03",
    "priceDateDisplay": "03/12/2026",
    "cacheHit": true,
    "cacheTtlRemainingSeconds": 3412,
    "isStale": false,
    "totalItems": 6
  },
  "data": [
    {
      "name": "Xăng E10 RON 95-III",
      "unit": "VND/lít",
      "region1": 18580,
      "region2": 18950,
      "sources": [
        { "source": "petrolimex", "region1": 18580, "region2": 18950, "price": null },
        { "source": "pvoil", "region1": null, "region2": null, "price": 18580 }
      ]
    }
  ]
}
```

### GET /api/v1/fuel-prices/{source}

Prices from one source. `meta.sourceUrl` is the official page to verify against.

| Parameter | In | Required | Description |
| --- | --- | --- | --- |
| `source` | path | yes | Source ID, see [Data sources](#data-sources) |
| `refresh` | query | no | `1` to purge cache and re-scrape. Needs Bearer token |

Errors: `400 INVALID_SOURCE`, `401 UNAUTHORIZED`, `503 SOURCE_UNAVAILABLE`.

```bash
curl -s https://vietfuel-api.tranqui.workers.dev/api/v1/fuel-prices/pvoil
```

### GET /api/v1/fuel-prices/province/{slug}

Retail prices in one province or city. Each province belongs to Region 1 or Region 2 (`meta.region`).

| Parameter | In | Required | Description |
| --- | --- | --- | --- |
| `slug` | path | yes | Province slug, e.g. `ha-noi`, `ho-chi-minh`, `lao-cai` |

Errors: `404 PROVINCE_NOT_FOUND`, `502 UPSTREAM_SCRAPE_ERROR`.

```bash
curl -s https://vietfuel-api.tranqui.workers.dev/api/v1/fuel-prices/province/ha-noi
```

### GET /api/v1/provinces

All 63 provinces and their pricing zone.

| Parameter | In | Required | Description |
| --- | --- | --- | --- |
| `region` | query | no | `1` or `2` |
| `q` | query | no | Case-insensitive match on name or slug |

```bash
curl -s "https://vietfuel-api.tranqui.workers.dev/api/v1/provinces?region=2"
```

### GET /api/v1/sources

All 12 sources with official URLs and cache status (`populated`, `scrapedAt`, `ttlRemainingSeconds`, `isStale`).

### GET /api/v1/history

Stored price snapshots (Cloudflare D1 or SQLite), retained for 90 days. Also available as `GET /api/v1/history/{fuel_name}`.

| Parameter | In | Required | Description |
| --- | --- | --- | --- |
| `fuel` | query | no | Partial product name, e.g. `RON 95` |
| `source` | query | no | Source ID |
| `from`, `to` | query | no | Date range `YYYY-MM-DD` |
| `limit` | query | no | `1`–`500`, default `100` |
| `offset` | query | no | Default `0` |

Errors: `400 VALIDATION_ERROR`, `501 DATABASE_NOT_CONFIGURED`.

```bash
curl -s "https://vietfuel-api.tranqui.workers.dev/api/v1/history?fuel=RON%2095&limit=20"
```

### GET /api/v1/health

System status (`healthy` or `degraded`), version, storage backends and per-source TTL. Never cached.

### POST /api/v1/admin/cache/clear

Clears every cached price. Needs `Authorization: Bearer <ADMIN_TOKEN>`.

### POST /api/v1/admin/scrape

Re-scrapes immediately. Without `source` it scrapes every source and prunes history older than 90 days. Needs Bearer token.

| Parameter | In | Required | Description |
| --- | --- | --- | --- |
| `source` | query | no | Scrape only one source |

```bash
curl -X POST "https://vietfuel-api.tranqui.workers.dev/api/v1/admin/scrape?source=petrolimex" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
```

Locally (`npm run dev` or `npm run dev:node`) the server runs in `development` mode, so admin endpoints work without a token. In production, admin endpoints always return `401` until `ADMIN_TOKEN` is set.

## Data sources

| ID (`source`) | Distributor | Price type | Official page to verify |
| --- | --- | --- | --- |
| `petrolimex` | Petrolimex | Region 1 + Region 2 | https://www.petrolimex.com.vn |
| `kv2_petrolimex` | Petrolimex KV2 (mirror) | Region 1 + Region 2 | https://kv2.petrolimex.com.vn |
| `saigon_petrolimex` | Petrolimex Sài Gòn (mirror) | Region 1 + Region 2 | https://saigon.petrolimex.com.vn |
| `vungtau_petrolimex` | Petrolimex Vũng Tàu (mirror) | Region 1 + Region 2 | https://vungtau.petrolimex.com.vn |
| `pvoil` | PVOil | Flat | https://www.pvoil.com.vn/tin-gia-xang-dau |
| `mipec` | Mipec | Region 1 + Region 2 | https://www.mipec.com.vn/pages/gia-xang-dau-ban-le |
| `comeco` | COMECO | Flat | https://comeco.vn |
| `saigonpetro` | Saigon Petro | Flat | https://saigonpetro.com.vn/ban-le-xang-dau |
| `petrotimes` | Petro Times | Region 1 + Region 2 | https://petrotimesgroup.com |
| `webgia` | WebGia | Region 1 + Region 2 | https://webgia.com/gia-xang-dau/petrolimex/ |
| `giaxanghomnay` | GiaXangHomNay | Region 1 + Region 2 | https://giaxanghomnay.com |
| `luatvietnam` | LuatVietnam | Flat | https://luatvietnam.vn/bang-gia-xang-dau-hom-nay.html |

The three Petrolimex mirrors share data with `petrolimex`.

## For developers

### Quick start

JavaScript / TypeScript:

```js
const res = await fetch('https://vietfuel-api.tranqui.workers.dev/api/v1/fuel-prices');
if (!res.ok) throw new Error((await res.json()).error.message);
const { meta, data } = await res.json();

console.log('Effective from', meta.priceDateDisplay);
for (const item of data) {
  console.log(item.name, item.region1, item.region2);
}
```

Python:

```python
import requests

r = requests.get("https://vietfuel-api.tranqui.workers.dev/api/v1/fuel-prices/province/ha-noi", timeout=10)
r.raise_for_status()
body = r.json()
for item in body["data"]:
    print(item["name"], item["region1"] or item["region2"])
```

PHP:

```php
$json = json_decode(file_get_contents('https://vietfuel-api.tranqui.workers.dev/api/v1/fuel-prices'), true);
foreach ($json['data'] as $item) {
    echo $item['name'] . ': ' . $item['region1'] . PHP_EOL;
}
```

### Best practices

- **Cache on your side**: respect `Cache-Control`. Prices change about once a week; polling every 15–60 minutes is plenty.
- **Handle errors**: always check `success`. On `503`, retry after 30–60 seconds. On `4xx`, read `error.code` and fix the request.
- **`null` values**: render `—`, not `0`. For flat-price sources, read `price` instead of `region1`.
- **Matching products**: product names are normalized (e.g. `Xăng E10 RON 95-III`, `DO 0,05S-II`) and safe to use as keys.
- **Versioning**: use `/api/v1/*`. Breaking changes will ship as `/api/v2/*`; new fields may be added to v1 at any time.
- **SDKs**: import `/openapi.json` into Postman, Bruno, Insomnia or `openapi-generator` for a typed client.

### HTTP status & error codes

| HTTP | `error.code` | Meaning |
| --- | --- | --- |
| 200 | — | Success — full JSON payload or asset returned |
| 304 | — | **Not Modified (not an error):** The browser/client sent a conditional cache header (`If-None-Match` / `If-Modified-Since`) and the static asset (CSS, JS, logo, `/docs.en.md`, etc.) has not changed, so the server returns an empty body to reuse the local cache — saving bandwidth and cutting load times |
| 400 | `INVALID_SOURCE`, `VALIDATION_ERROR` | Bad source ID or parameter |
| 401 | `UNAUTHORIZED` | Missing or wrong Bearer token on an admin endpoint |
| 403 | `FORBIDDEN` | Blocked User-Agent (scanner tools) |
| 404 | `PROVINCE_NOT_FOUND`, `NOT_FOUND` | Unknown province slug or path |
| 405 | `METHOD_NOT_ALLOWED` | Wrong HTTP method |
| 413 | `PAYLOAD_TOO_LARGE` | Payload over 4 KB |
| 501 | `DATABASE_NOT_CONFIGURED` | Server has no D1/SQLite for history |
| 502 | `UPSTREAM_SCRAPE_ERROR` | The province source page failed to load |
| 503 | `SERVICE_UNAVAILABLE`, `SOURCE_UNAVAILABLE` | Source is down and no valid cache remains |

## Terminal CLI

```bash
npm run cli                                  # interactive menu, pick by number
npm run cli -- prices --zone both            # comparison table, --zone 1 | 2 | both
npm run cli -- source pvoil
npm run cli -- province ha-noi
npm run cli -- provinces --region 2 --q lao
npm run cli -- history --fuel "RON 95" --limit 20
npm run cli -- health
npm run cli -- prices --json                 # raw JSON to pipe into jq
```

The CLI probes `http://localhost:8787`, then `http://localhost:3000`, then falls back to production. Override with `--url <baseUrl>` or `VIETFUEL_API_URL`. The interface defaults to Vietnamese; use `--lang en` or `VIETFUEL_LANG=en` for English.

## For AI and agents

### Machine-readable resources

| Resource | Use |
| --- | --- |
| `/llms.txt` | Short index following llmstxt.org |
| `/llms-full.txt` | The full English docs in one file |
| `/docs.md`, `/docs.en.md` | Markdown docs (Vietnamese / English) |
| `/openapi.json` | OpenAPI 3.1 spec for every endpoint |

### Rules for answering users

- Latest prices: call `GET /api/v1/fuel-prices`, read `data[].region1` (Region 1) and `data[].region2` (Region 2). The effective date is `meta.priceDate`.
- One province: call `GET /api/v1/provinces?q=<name>` to get the `slug`, then `GET /api/v1/fuel-prices/province/<slug>`.
- Compare sources: use `data[].sources[]`. For flat-price sources, read `price`.
- Never guess a price when a field is `null`. Always state the effective date and the unit VND/litre.
- Cite `meta.sourceUrl` or the URL in the sources table.
- Freshness: `meta.isStale = true` or `X-Cache: STALE` means data is past its TTL but within the 6-hour limit.

### Tool definition (function calling)

Paste into the `tools` array for OpenAI, Anthropic, Gemini or an MCP server:

```json
{
  "name": "get_vietnam_fuel_prices",
  "description": "Get current Vietnam retail fuel prices (VND/litre). Optionally for one province or one distributor.",
  "parameters": {
    "type": "object",
    "properties": {
      "province_slug": { "type": "string", "description": "Province slug such as ha-noi or ho-chi-minh. Get it from /api/v1/provinces?q=" },
      "source": { "type": "string", "enum": ["petrolimex", "pvoil", "mipec", "comeco", "saigonpetro", "petrotimes", "webgia", "giaxanghomnay", "luatvietnam"] }
    }
  }
}
```

HTTP mapping: with `province_slug` call `/api/v1/fuel-prices/province/{province_slug}`; with `source` call `/api/v1/fuel-prices/{source}`; otherwise call `/api/v1/fuel-prices`.

### System prompt template

```text
You are a Vietnam fuel price assistant. Use only data from VietFuel API (https://vietfuel-api.tranqui.workers.dev).
Always state the effective date (meta.priceDate) and the unit VND/litre. Distinguish Region 1, Region 2 and Flat prices.
If a price is null, say no data is available. Include the source page link so the user can verify.
```

## Self-hosting

```bash
# Cloudflare Workers
npx wrangler kv namespace create FUEL_CACHE
npx wrangler d1 create vietfuel-history
npx wrangler d1 execute vietfuel-history --remote --file=./src/db/schema.sql
npx wrangler secret put ADMIN_TOKEN
npm run deploy

# Node.js or Docker
npm run dev:node
docker compose up -d --build
```

## Legal

Data is collected automatically from public websites for reference only. The project is independent and does not represent any company or government agency. Source code is MIT licensed.
