# Brazil Public Procurement / PNCP Licitações (`jccdev7/pncp-licitacoes`) Actor

Busca licitações e contratações públicas no Portal Nacional de Contratações Públicas (PNCP) por UF, palavra-chave ou nicho e exporta JSON/CSV. Brazil public procurement scraper for PNCP tenders and bids via the official API — no API key. Filter by state, keyword, modality and open proposal deadline.

- **URL**: https://apify.com/jccdev7/pncp-licitacoes.md
- **Developed by:** [Sempre Crypto Milionário](https://apify.com/jccdev7) (community)
- **Categories:** Business, Lead generation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 77.8% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 tender results

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

This **Brazil public procurement / PNCP licitações scraper** searches public tenders and contracts on the [Portal Nacional de Contratações Públicas (PNCP)](https://pncp.gov.br) through the [official public consultation API](https://pncp.gov.br/api/consulta/swagger-ui/index.html). It needs **no API key**. Results are saved as a JSON dataset and, optionally, as a CSV file.

Este Actor busca **licitações e contratações públicas** no PNCP pela API oficial de consulta, sem chave de acesso, e devolve os resultados em JSON e CSV.

It is **not an official service of the Brazilian government**. Data comes from the public PNCP API and may be delayed or fail if the portal is unstable. Always confirm notices on [pncp.gov.br](https://pncp.gov.br) before bidding.

Não é um serviço oficial do governo brasileiro. Os dados vêm da API pública do PNCP e podem atrasar ou falhar se o portal estiver instável. Confira sempre o edital no portal antes de participar.

On the [Apify](https://apify.com) platform you can run the Actor from the Console or via API, schedule recurring searches, monitor runs, export results (JSON, CSV, Excel and others) and connect them to other tools.

### What is this Actor? / O que este Actor faz?

Use it to extract **PNCP licitações** (Brazil public procurement notices) filtered by:

- Brazilian state (**UF**), or the whole country
- Keyword in the tender object (all words must match)
- Ready-made niche (cleaning, foodstuffs, IT/software, construction/renovation, transport/freight)
- Publication window (last N days, or an explicit date range of up to 90 days)
- Procurement modality (default: electronic auction / *pregão eletrônico* and electronic bidding / *concorrência eletrônica*)
- Open proposal deadline only (on by default)

Serve para acompanhar editais por estado, palavra no objeto, nicho, janela de publicação, modalidade e prazo de propostas ainda aberto.

### How to use / Como usar

1. Open the Actor on Apify Store or in [Apify Console](https://console.apify.com) and click **Try for free** / **Start**.
2. Choose a **UF** (leave empty for all of Brazil — slower), a **palavra-chave**, and/or a **nicho**.
3. Keep the default window (last 10 days) or set `dataInicial` and `dataFinal` (`YYYY-MM-DD`, max 90 days).
4. Keep **Só com prazo de propostas aberto** on if you only want tenders still accepting proposals.
5. Set **Máximo de itens** (default 100, max 1000) and run.
6. Download the dataset as JSON/CSV/Excel, or grab `licitacoes.csv` and `SUMMARY.json` from the key-value store.

The input form stays in Portuguese. Field names and behavior are unchanged.

### Input / Entrada

| Field / Campo | Description / Descrição |
| --- | --- |
| **UF** | Optional state acronym. Empty = all of Brazil. |
| **Palavra-chave** | Text in the tender object. Every word must appear (case-insensitive). Examples: `limpeza`, `merenda`, `software`. |
| **Nicho** | Ready filter: limpeza, gêneros alimentícios, TI e software, obras e reformas, transporte e frete. If used with a keyword, the item must match both. |
| **Janela de publicação (dias)** | Notices published in the last N days (default 10). Ignored when both dates are set. |
| **Data inicial / Data final** | `AAAA-MM-DD`. Together they replace the day window (max 90 days). |
| **Modalidades** | PNCP API codes. Default is 6 (pregão eletrônico) and 4 (concorrência eletrônica). |
| **Só com prazo de propostas aberto** | On by default. Items without an end date are kept. |
| **Máximo de itens no resultado** | Stops when this many filtered items are reached (default 100, max 1000). |
| **Gerar arquivo CSV** | Also writes `licitacoes.csv` to the run's key-value store. |

Example input:

```json
{
  "uf": "RS",
  "palavraChave": "limpeza",
  "nicho": "",
  "dias": 10,
  "modalidades": [6, 4],
  "apenasPropostasAbertas": true,
  "maxItens": 10,
  "gerarCsv": true
}
```

### Output / Saída

Each dataset item includes: PNCP id, object, contracting authority, CNPJ, unit, municipality, UF, modality, estimated value, publication / opening / closing dates, SRP flag, process number, and the [notice link](https://pncp.gov.br) on the portal.

Cada item inclui id do PNCP, objeto, órgão, CNPJ, unidade, município, UF, modalidade, valor estimado, datas, processo e o link do edital no portal.

A run summary is stored as `SUMMARY.json`.

### Pricing / Preço

This Actor is designed for **pay-per-event (PPE)** on Apify Store:

- Custom event **`result-item`**: one charge per licitação / tender written to the dataset.
- Apify also recommends keeping the synthetic **`apify-actor-start`** event (default about $0.00005 per start, with the first 5 seconds of compute covered).

The exact event prices are set in the Actor's **Publishing** tab in Apify Console at publish time. They are not hardcoded here.

**Free plan notes:** users on the Apify free plan can run the Actor, but usage by free-plan users does **not** generate creator revenue (Apify covers their platform usage). Paid-plan users pay for the events above. Local runs are never billed.

Nada é cobrado na execução local. O preço na Store só é configurado no Console da Apify na hora de publicar.

### Data source and disclaimer / Fonte dos dados e aviso

- API base: `https://pncp.gov.br/api/consulta`
- Endpoint used: `GET /v1/contratacoes/publicacao`
- Docs: [PNCP consultation API Swagger](https://pncp.gov.br/api/consulta/swagger-ui/index.html) and [PNCP open data](https://www.gov.br/pncp/pt-br/acesso-a-informacao/dados-abertos)

This tool only reads **public official data**. It does not bypass access controls, submit bids, or change notices. It is not affiliated with, endorsed by, or part of the Brazilian government or the PNCP. If the official API is slow, rate-limits, or returns errors, the run retries with backoff, skips a failed page if needed, and still finishes with any results already collected plus a warning in `SUMMARY.json`. Treat results as a starting point and validate them on the official portal.

Esta ferramenta só lê dados públicos oficiais. Não envia propostas nem altera editais. Não é afiliada ao governo brasileiro nem ao PNCP.

### How to run locally / Como rodar localmente

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
## optional: npm install -g apify-cli
cp input.example.json storage/key_value_stores/default/INPUT.json
ACTOR_TEST_PAY_PER_EVENT=true apify run --purge
## if the CLI is not installed:
## ACTOR_TEST_PAY_PER_EVENT=true python -m my_actor
```

### FAQ

**Is this the official PNCP API / Isso é a API oficial?**
The Actor calls the official public consultation API. The Actor itself is an independent tool, not a government product.

**Do I need an API key?**
No.

**Can I search all of Brazil?**
Yes. Leave **UF** empty. The query takes longer because every selected modality is paged for the whole country, and each modality is capped at 40 pages so the run can finish before the platform timeout.

**Why are some notices missing?**
Filters (keyword, niche, open deadline, modalities, max items) or a temporary PNCP outage can exclude or delay items. Widen the window or turn off the open-deadline filter to check. A whole-Brazil search also stops after 40 pages per modality (2,000 notices scanned in that modality) so the run can finish in time.

**How do I get data via API or on a schedule?**
Use Apify's Actor API, saved tasks, and schedules after you run it once in Console.

### Limits and safeguards / Limites e proteções

The Actor is built to finish as **SUCCEEDED** whenever possible, including on heavy or messy input:

- **Newest first / mais recentes primeiro:** long publication windows are queried in 7-day slices starting from the end date, because the PNCP API pages oldest items first. This finds still-open tenders sooner. / Janelas longas são consultadas em fatias de 7 dias a partir da data final.
- **Time budget / orçamento de tempo:** it reads the platform timeout (`APIFY_TIMEOUT_AT` / `ACTOR_TIMEOUT_AT`), stops about 45 seconds before the limit, saves whatever it already found, and ends successfully with a warning in `SUMMARY.json` and in the run status message. You still receive partial results instead of a `TIMED-OUT` run.
- **Whole-Brazil page cap / limite de páginas no Brasil inteiro:** when **UF** is empty, each modality is capped at **40 pages** (50 items per page). Narrow the search with a UF, keyword, or niche if you need a deeper scan.
- **Invalid input / entrada inválida:** bad values are clamped to safe defaults when that makes sense (for example a date window longer than 90 days is cut to the most recent 90 days; `dataInicial` after `dataFinal` is swapped; unknown UF/niche/modality is ignored). The run does not crash with a traceback.
- **PNCP errors:** HTTP 429, 5xx and network timeouts are retried with backoff. If a page still fails, it is skipped and the run continues with the data already collected.
- **Pay-per-event cap:** items are charged as `result-item` when they are written to the dataset. If the run reaches the user-set **max total charge**, it stops cleanly, keeps the items already saved, and finishes successfully.

O Actor tenta terminar sempre com sucesso: para ~45 s antes do timeout da plataforma, limita a busca nacional a 40 páginas por modalidade, ajusta entradas inválidas, não cai em erro se o PNCP falhar depois das retentativas e respeita o limite máximo de cobrança.

# Actor input Schema

## `uf` (type: `string`):

Sigla da unidade federativa da unidade administrativa. Deixe vazio para buscar em todo o Brasil (a consulta fica mais lenta).

## `palavraChave` (type: `string`):

Texto buscado no objeto da contratação. Se houver várias palavras, todas precisam aparecer (sem distinguir maiúsculas). Exemplos: limpeza, merenda, software.

## `nicho` (type: `string`):

Filtro pronto por padrões no objeto. Se você também preencher a palavra-chave, o item precisa casar com os dois.

## `dias` (type: `integer`):

Contratações publicadas no PNCP nos últimos N dias (incluindo hoje). Ignorado se dataInicial e dataFinal forem preenchidas.

## `dataInicial` (type: `string`):

Formato AAAA-MM-DD. Se preenchida junto com a data final, substitui a janela em dias.

## `dataFinal` (type: `string`):

Formato AAAA-MM-DD. Se preenchida junto com a data inicial, substitui a janela em dias.

## `modalidades` (type: `array`):

Códigos de modalidade da API de consulta do PNCP. O padrão cobre as duas mais usadas em disputa: pregão eletrônico (6) e concorrência eletrônica (4).

## `apenasPropostasAbertas` (type: `boolean`):

Se ligado, descarta contratações cuja data de encerramento das propostas já passou. Itens sem essa data são mantidos.

## `maxItens` (type: `integer`):

A busca para quando atinge esse número de itens filtrados. Use um valor menor para testes rápidos.

## `gerarCsv` (type: `boolean`):

Além do dataset JSON, grava licitacoes.csv no key-value store da execução.

## Actor input object example

```json
{
  "uf": "RS",
  "palavraChave": "limpeza",
  "nicho": "",
  "dias": 10,
  "modalidades": [
    "6",
    "4"
  ],
  "apenasPropostasAbertas": true,
  "maxItens": 100,
  "gerarCsv": true
}
```

# Actor output Schema

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

No description

## `csv` (type: `string`):

No description

## `resumo` (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 = {
    "uf": "RS",
    "palavraChave": "limpeza",
    "dias": 10,
    "modalidades": [
        "6",
        "4"
    ],
    "apenasPropostasAbertas": true,
    "maxItens": 100,
    "gerarCsv": true
};

// Run the Actor and wait for it to finish
const run = await client.actor("jccdev7/pncp-licitacoes").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 = {
    "uf": "RS",
    "palavraChave": "limpeza",
    "dias": 10,
    "modalidades": [
        "6",
        "4",
    ],
    "apenasPropostasAbertas": True,
    "maxItens": 100,
    "gerarCsv": True,
}

# Run the Actor and wait for it to finish
run = client.actor("jccdev7/pncp-licitacoes").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 '{
  "uf": "RS",
  "palavraChave": "limpeza",
  "dias": 10,
  "modalidades": [
    "6",
    "4"
  ],
  "apenasPropostasAbertas": true,
  "maxItens": 100,
  "gerarCsv": true
}' |
apify call jccdev7/pncp-licitacoes --silent --output-dataset

```

## MCP server setup

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

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/yOXIoxCkFdr5JAQOz/builds/aMmkIcJRBTdmVWPrw/openapi.json
