# Portugal Public Contracts & Tenders (BASE) (`goncalocalvo/portugal-public-contracts-base`) Actor

Structured, filterable Portuguese public procurement data (contracts, tender announcements, contract modifications) from the official IMPIC / Portal BASE open data on dados.gov.pt. Weekly refresh. Unofficial.

- **URL**: https://apify.com/goncalocalvo/portugal-public-contracts-base.md
- **Developed by:** [Gonçalo Calvo](https://apify.com/goncalocalvo) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 records

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

## Portugal Public Contracts & Tenders (BASE)

Structured, filterable access to **Portugal public procurement** data: awarded public contracts (*contratos públicos*), tender announcements (*anúncios de concurso*) and contract modifications, as published by IMPIC from **Portal BASE** on the official open data portal dados.gov.pt.

This Actor is **unofficial**. It is not affiliated with, endorsed by or operated by IMPIC, Portal BASE, dados.gov.pt or any Portuguese public body.

### What it does

- Returns contracts, announcements or contract modifications as clean JSON with stable English field names. The values stay in Portuguese, exactly as published.
- Filters by publication date, CPV code prefix, Portuguese keywords, district and municipality, value range and contracting authority.
- Has a **monitor mode** that returns only the records that are new since your previous run.
- Uses **only official open data files**. It does not scrape any website, does not read contract PDFs and does not touch login-protected areas.

#### Data freshness: weekly, not real time

IMPIC regenerates the source files **once a week** (normally on Sunday). This Actor reads a cache rebuilt from those files, so:

- Every item carries `snapshot_date`, the date of the weekly snapshot it came from.
- The newest records can be up to about 8 days old. About one in five Portuguese tenders has a proposal deadline of 7 days or less, so this Actor is **not** a reliable same-day alert for short-deadline tenders. It is built for market research, award analysis and weekly digests.
- If the weekly refresh is overdue (snapshot older than 14 days), the run still works but every item has `snapshot_stale: true` and the log shows a warning.

#### Coverage

A rolling window of the **last 10 years**, counted back from the day of the run. Older dates in `dateFrom` are moved forward automatically.

### Use cases

- **Supplier alerts (weekly):** schedule a weekly monitor for your CPV codes and keywords and receive only the new tenders and awards.
- **Market research and award analysis:** who buys what, from whom and at what price; value by CPV, region or authority; competitor wins.
- **AI agents and MCP:** call the Actor as a tool through the Apify MCP server. Inputs are self-describing and the output is compact, so an agent can answer questions such as "which IT contracts above 50,000 EUR did Lisbon municipalities sign last month?".

### Input

All fields are optional. With an empty input you get the latest 100 contracts published in the last 30 days.

| Field | Type | Description |
|---|---|---|
| `datasetType` | string | `contracts` (default), `announcements` or `modifications`. |
| `dateFrom`, `dateTo` | string | Publication date range, `YYYY-MM-DD`. Default: the last 30 days. |
| `cpvPrefixes` | string\[] | CPV code prefixes, 2 to 8 digits, e.g. `["72", "4521"]`. |
| `keywords` | string\[] | Portuguese words or phrases; any match; case and accents ignored. |
| `district`, `municipality` | string | Place of execution. Contracts and modifications only. |
| `minValue`, `maxValue` | number | Value range in EUR (contract price, base price or new price). |
| `contractingAuthority` | string | 9-digit tax number (NIF) or part of the buyer's name. |
| `maxItems` | integer | 1 to 50,000, default 100. Newest first. |
| `includeBidders` | boolean | Contracts only: add the list of bidders. Default `false`. |
| `monitor` | boolean | Return only records new since your last monitor run. |
| `monitorKey` | string | Optional name, to keep several independent monitors. |

The announcements dataset has no location field. Using `district` or `municipality` with `announcements` returns an error item instead of silently ignoring the filter.

#### Example input

```json
{
    "datasetType": "contracts",
    "dateFrom": "2026-10-01",
    "dateTo": "2026-10-31",
    "cpvPrefixes": ["72"],
    "keywords": ["software"],
    "district": "Lisboa",
    "minValue": 50000,
    "maxItems": 200
}
```

#### Monitor mode

- The first run with `monitor: true` returns the normal results for your date range and stores a baseline.
- Later runs return only records that first appeared in a snapshot newer than the one you last saw. If there is no newer snapshot, you get a single `no_results` item.
- After the baseline, when you give no `dateFrom`, the Actor looks back 45 days before your last snapshot so that late publications are not missed.
- The only state kept is the last snapshot date, in a key-value store named `base-pt-monitor-state` in **your** account.

> **Warning: truncated monitor runs are charged again.** If `maxItems` or your maximum charge limit cuts a monitor run short, the monitor state does **not** advance. Nothing is lost, but the next run returns the same new records from the start, and you pay for them again. For monitor runs, set `maxItems` high enough for a whole week of new records (1,000 or more for narrow filters; unfiltered contracts grow by about 5,000 a week) and a matching maximum charge. The Actor logs a warning when a monitor run uses `maxItems` below 1,000 and when a run was truncated.

### Output

One dataset item per record. Example contract (illustrative values):

```json
{
    "record_type": "contract",
    "id": "9000004",
    "snapshot_date": "2026-11-08",
    "snapshot_stale": false,
    "first_seen_snapshot": "2026-11-08",
    "publication_date": "2026-11-06",
    "signing_date": "2026-11-06",
    "object": "Empreitada de reabilitação de edifício escolar",
    "description": "Obras de reabilitação da Escola Básica de Exemplo",
    "procedure_type": "Ajuste Direto Regime Geral",
    "contract_types": ["Empreitadas de obras públicas"],
    "cpv": [{ "code": "45210000-2", "description": "Construção de edifícios" }],
    "contract_value_eur": 150000.0,
    "base_price_eur": 150000.0,
    "execution_days": 81,
    "execution_locations": ["Portugal, Porto, Porto"],
    "contracting_authorities": [{ "nif": "600000010", "name": "Município de Exemplo Norte" }],
    "awardees": [
        { "nif": null, "name": "[REDACTED]", "country": "PRT", "redacted": true },
        { "nif": "980000017", "name": "Sucursal Exemplo, S.A.", "country": "PRT", "redacted": false }
    ],
    "bidders_count": 2,
    "invited_count": 0,
    "procedure_documents_url": null,
    "announcement_id": null,
    "base_record_url": "https://www.base.gov.pt/Base4/pt/detalhe/?type=contratos&id=9000004",
    "source": "dados.gov.pt / IMPIC (Portal BASE)"
}
```

Fields by record type:

- **All:** `record_type`, `id`, `snapshot_date`, `snapshot_stale`, `first_seen_snapshot`, `publication_date`, `source`.
- **Contracts:** `signing_date`, `object`, `description`, `procedure_type`, `contract_types`, `cpv`, `contract_value_eur`, `base_price_eur`, `execution_days`, `execution_locations`, `contracting_authorities`, `awardees`, `bidders_count`, `bidders` (only with `includeBidders`), `invited_count`, `procedure_documents_url`, `announcement_id`, `base_record_url` (the contract's page on Portal BASE).
- **Announcements:** `notice_number`, `notice_type`, `procedure_model`, `description`, `contract_types`, `cpv`, `base_price_eur`, `deadline_date`, `deadline_days`, `contracting_authorities`, `lots_count`, `announcement_url` (the official notice in Diário da República), `procedure_documents_url`.
- **Modifications:** `contract_id`, `modification_date`, `new_price_eur`, `new_execution_days`, `reason`, `act_type`, `base_record_url` (the modified contract's page on Portal BASE), and `contract` (object, CPV, value, buyers and locations of the modified contract; `null` when that contract is outside the 10-year window).

The source has no ID for modifications, so their `id` is the contract ID plus a short hash of the record.

#### Empty and invalid runs

A run never ends with an empty dataset:

- No matching records: one item with `record_type: "no_results"` and a `message`.
- Invalid input: one item with `record_type: "error"` and a `message` that says what to fix.

### Pricing

Pay per event:

| Event | Price |
|---|---|
| Actor start (charged by Apify) | $0.00005 per run |
| Record | $0.002 per item, i.e. **$2.00 per 1,000 records** |

- The single `no_results` or `error` item of an empty or invalid run is charged as one record ($0.002).
- If the Actor fails because of a problem on our side (for example the data cache is unavailable), the run fails and **no record is charged**.
- `maxItems` and Apify's maximum-cost-per-run setting both cap what a run can cost. The Actor stops cleanly when your limit is reached.

### Personal data (GDPR)

Public procurement data names the parties to each contract, and some of them are natural persons (for example sole traders and individual service providers). This Actor keeps entity-level data only:

- A counterparty's name and tax number are shown only when the tax number (NIF) is valid and its prefix identifies an entity: 5 (companies), 6 (public bodies), 71, 72, 98 or 99.
- Every other awardee or bidder is replaced by `"name": "[REDACTED]"` with `"redacted": true`. The contract itself is kept. This rule is deliberately strict, so it also hides foreign companies that have no Portuguese tax number.
- Invited entities are reported as a count only.
- Redaction and masking are applied before the data reaches the cache, so redacted values are not stored anywhere by this Actor.

#### Free-text fields: best-effort masking

The `object`, `description` and `reason` fields are written by the contracting authorities and sometimes mention people. Before the data reaches the cache, the Actor masks:

- **A person title followed by a name** (Dr., Dra., Eng., Eng.ª, Prof., Prof.ª, Sr., Sra., Arq. and the spelled-out forms): `com a Dra. Maria Silva` becomes `com a Dra. [REDACTED]`.
- **E-mail addresses.**
- **Phone numbers** introduced by "tel", "telefone" or "contacto".
- **Tax numbers** introduced by "NIF", "NIPC" or "contribuinte".

Names of streets, schools, hospitals and similar places are kept (`Rua Dr. António ...`, `Escola Prof. ...`, `Hospital Dr. ...`), because they are public place names and not parties to the contract. Bare 9-digit numbers are left alone; they are almost always reference numbers.

**This masking is best-effort.** It works on patterns, so:

- A name written **without a title** is not detected and may remain.
- A person's name can occasionally be kept because it follows a place word, and a place name can occasionally be masked.
- In the 2026 data about 0.25% of records have a masked value.

**Removal requests:** if you find personal data in the output, yours or someone else's, report it in the Actor's **Issues** tab so that it can be removed.

You remain responsible for using the data in line with the GDPR and any other law that applies to you.

### Data source and licence

- **Source:** IMPIC - Instituto dos Mercados Públicos, do Imobiliário e da Construção, I.P., datasets "Contratos Públicos - Portal Base - IMPIC" (Contratos, Anúncios, Modificações Contratuais) on [dados.gov.pt](https://dados.gov.pt/).
- **Licence as shown on dados.gov.pt for these datasets:** "Outra (Domínio Público)". The dados.gov.pt terms of use also state that data published by State bodies is under Creative Commons CC BY 4.0 unless specified otherwise; attribution to IMPIC and dados.gov.pt is given here in either case.
- **Legal basis for reuse:** Portaria n.º 318-B/2023, Art. 6.º n.º 2, which states that the public data of Portal BASE may be extracted automatically, free of charge and in open formats, through the portal itself and other public portals, namely dados.gov.pt.
- The Actor downloads the files once per weekly snapshot, sequentially and with pauses. It never queries base.gov.pt.

### Limitations

- Weekly refresh; see "Data freshness" above.
- Contracts and modifications link to the contract page on base.gov.pt. Announcements link to the official Diário da República notice instead.
- `procedure_documents_url` is given only when the source holds a well-formed public link; it may point to a platform that requires registration to download the documents.
- Records are republished as provided by IMPIC. Errors in the source (wrong values, missing CPV, duplicate entries) are not corrected.
- Announcements cannot be filtered by location.

### Em português

Este Actor dá acesso estruturado aos dados abertos da **contratação pública portuguesa** publicados pelo IMPIC a partir do **Portal BASE** em dados.gov.pt: contratos públicos, anúncios de procedimento e modificações contratuais.

- **Não é um serviço oficial.** Não tem qualquer ligação ao IMPIC, ao Portal BASE ou ao dados.gov.pt.
- **Atualização semanal:** os ficheiros de origem são regenerados uma vez por semana. Cada registo indica a data do snapshot em `snapshot_date`. Não serve para alertas no próprio dia.
- **Filtros:** datas de publicação, prefixos CPV, palavras-chave (sem distinção de acentos ou maiúsculas), distrito e concelho, intervalo de valores e entidade adjudicante (nome ou NIF).
- **Modo monitor:** devolve apenas os registos novos desde a execução anterior.
- **Dados pessoais:** só são mostrados nomes de entidades com NIF válido de pessoa coletiva ou organismo público; os restantes adjudicatários e concorrentes aparecem como `[REDACTED]`. Nos campos de texto livre são ocultados, na medida do possível, nomes precedidos de título (Dr., Eng., Prof., Sr., ...), endereços de e-mail, telefones e NIF. Esta ocultação não é perfeita: nomes sem título podem permanecer. Se encontrar dados pessoais, peça a sua remoção no separador **Issues** do Actor.
- **Fonte:** IMPIC, I.P. / dados.gov.pt, licença indicada no portal: "Outra (Domínio Público)". Reutilização ao abrigo do artigo 6.º, n.º 2, da Portaria n.º 318-B/2023.
- **Janela temporal:** últimos 10 anos.

### Local development

```bash
python -m venv .venv
.venv/Scripts/python -m pip install -r requirements-dev.txt   # Linux/macOS: .venv/bin/python
.venv/Scripts/python -m pytest
apify run --purge --input-file sample_input.json
```

A local run with no configuration reads `sample_cache/`, a tiny synthetic cache built from the test fixtures. Set `BASE_PT_CACHE_DIR` to read another local cache. Pay-per-event events are configured in Apify Console; `.actor/pay_per_event.json` is only a reference copy of the values.

# Actor input Schema

## `datasetType` (type: `string`):

Which dataset to query. 'contracts' = awarded/signed contracts with buyer, awardee, value, CPV and location. 'announcements' = tender notices published in Diário da República, with deadline and base price. 'modifications' = amendments to existing contracts (new price, new duration, reason).

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

Earliest publication date, format YYYY-MM-DD. Default: 30 days before 'Published to'. Data older than 10 years before today is not served; an older date is moved forward automatically.

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

Latest publication date, format YYYY-MM-DD. Default: today. The data is a weekly snapshot, so the most recent days may not be available yet; check 'snapshot_date' in the output.

## `cpvPrefixes` (type: `array`):

Keep records whose CPV code starts with any of these prefixes (2 to 8 digits). Examples: '72' = IT services, '45' = construction works, '33' = medical equipment, '79' = business services, '09' = fuels. Leave empty for all CPVs.

## `keywords` (type: `array`):

Keep records whose object or description contains ANY of these words or phrases. Matching ignores case and accents ('reabilitacao' matches 'Reabilitação'). Use Portuguese terms, e.g. 'software', 'limpeza', 'empreitada'. Leave empty for no keyword filter.

## `district` (type: `string`):

District of the place of execution as written in BASE, e.g. 'Lisboa', 'Porto', 'Faro'. Case and accents are ignored. Works for 'contracts' and 'modifications' only: the announcements dataset has no location field, and the run returns an error item if this is set together with 'announcements'.

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

Municipality (concelho) of the place of execution, e.g. 'Loulé', 'Vila Nova de Gaia'. Case and accents are ignored. Works for 'contracts' and 'modifications' only (same restriction as 'district').

## `minValue` (type: `number`):

Minimum value in euros, without VAT. Applies to the contract price (contracts), the base price (announcements) or the new price (modifications). Records with no value are excluded when this is set.

## `maxValue` (type: `number`):

Maximum value in euros, without VAT. Same field as 'Minimum value'. Records with no value are excluded when this is set.

## `contractingAuthority` (type: `string`):

Public buyer to filter by: either its 9-digit tax number (NIF/NIPC, exact match, e.g. '600000010') or part of its name (case and accents ignored, e.g. 'Câmara Municipal de Almada').

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

Maximum number of records to return (1 to 50,000). Newest publication dates come first. Each returned record is one paid 'record' event, so this also caps the cost of the run. In monitor mode use a high value (1000 or more): a truncated monitor run repeats the same records next time.

## `includeBidders` (type: `boolean`):

Contracts only. If true, each contract includes a 'bidders' list (tax number and name of the entities that submitted a bid). Bidders that cannot be identified as companies or public bodies are redacted. If false, only 'bidders_count' is returned.

## `monitor` (type: `boolean`):

If true, return only records that first appeared in a data snapshot newer than your previous monitor run with the same monitor name. The first run returns the normal results and sets the baseline. The source is refreshed weekly, so running this more often than weekly mostly returns a single 'no_results' item. Important: if 'maxItems' or your maximum charge limit cuts a monitor run short, the state does not advance and the next run returns, and charges, the same records again; use maxItems of 1000 or more for monitor runs. State (only the last snapshot date) is stored in your own key-value store 'base-pt-monitor-state'.

## `monitorKey` (type: `string`):

Optional name that identifies this monitor (letters, digits, '-' and '\_', up to 60 characters). Use different names to keep independent monitors. Default: derived automatically from the dataset and filters.

## Actor input object example

```json
{
  "datasetType": "contracts",
  "maxItems": 100,
  "includeBidders": false,
  "monitor": false
}
```

# Actor output Schema

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

No description

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("goncalocalvo/portugal-public-contracts-base").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("goncalocalvo/portugal-public-contracts-base").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 '{}' |
apify call goncalocalvo/portugal-public-contracts-base --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,goncalocalvo/portugal-public-contracts-base"
        }
    }
}
```

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/ZR9afzYcMny5ajDxG/builds/SG5lmdZiGZxZ5pKDY/openapi.json
