# Spanish Law Scraper (BOE) - Consolidated Legislation for RAG (`flets_sv/boe-legislacion-consolidada`) Actor

Get Spanish consolidated laws from the official BOE API article by article: clean text, validity dates, version history and change alerts. Ready for legal RAG.

- **URL**: https://apify.com/flets_sv/boe-legislacion-consolidada.md
- **Developed by:** [FlEtsv](https://apify.com/flets_sv) (community)
- **Categories:** AI, Developer tools
- **Security:** Limited permissions
- **Stats:** 3 total users, 2 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

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

## Spanish Law Scraper (BOE) - Consolidated Legislation API for RAG

Download Spanish consolidated legislation from the official BOE open-data API, article by article: clean text, hierarchy, validity dates, version history and change monitoring. Built for legal RAG, compliance tools and AI agents. *Versión en español más abajo.*

***

### Use cases

- Ground legal RAG chatbots and AI assistants on official, up-to-date Spanish legislation
- Legal-tech products: compare article versions and track amendments
- Compliance monitoring for Spanish and EU-derived rules
- Research datasets of laws, decrees and codes

### English

#### What does it do?

The Actor calls the official **BOE (Boletín Oficial del Estado) open-data API** and returns every article of a Spanish law as one structured record, ready to index in a vector database. It supports the Constitution, Civil Code, Criminal Code, Workers' Statute, VAT and income-tax laws, the public procurement law and any other norm by BOE id or URL.

Use cases:

- **Legal RAG and AI assistants:** pre-chunked articles with hierarchical path and an official link to cite.
- **Legislative monitoring:** `soloCambios` emits only new or modified articles since your last run.
- **Point-in-time law:** `fechaVigencia` returns the text in force on a given date; `incluirHistorico` returns every version of each article.
- **Compliance analytics:** filter by subject, compare versions, track repeals.

#### Input

An empty input `{}` returns the first 20 articles of the Spanish Constitution (fast demo).

| Field | Description |
|---|---|
| `normas` | BOE ids (e.g. `BOE-A-1978-31229`) or boe.es URLs. |
| `codigosPredefinidos` | Shortcuts: `constitucion`, `codigo-civil`, `codigo-penal`, `codigo-comercio`, `estatuto-trabajadores`, `lec`, `ley-general-tributaria`, `ley-iva`, `ley-irpf`, `ley-sociedades-capital`, `ley-39-2015`, `lcsp`, `lopdgdd`, `lau`. |
| `tiposBloque` | `precepto` (articles, default), `encabezado`, `parte_dispositiva`, `firma`. |
| `fechaVigencia` | `YYYY-MM-DD`: version in force on that date. |
| `incluirHistorico` | Emit all versions of each article. |
| `soloCambios` | Only new or modified articles since the last run. |
| `formatoTexto` | `texto`, `markdown` or `html`. |
| `maxArticulos` | Spend and size cap (default 1000). |

```json
{ "codigosPredefinidos": ["ley-iva"], "formatoTexto": "markdown", "maxArticulos": 500 }
```

#### Output

Real item from a run with `{}`:

```json
{
  "idNorma": "BOE-A-1978-31229",
  "tituloNorma": "Constitución Española.",
  "rango": "Constitución",
  "departamento": "Cortes Generales",
  "ambito": "Estatal",
  "idBloque": "a1",
  "tipoBloque": "precepto",
  "tituloBloque": "Artículo 1",
  "numeroArticulo": "1",
  "ruta": ["TÍTULO PRELIMINAR"],
  "texto": "1. España se constituye en un Estado social y democrático de Derecho, que propugna como valores superiores de su ordenamiento jurídico la libertad, la justicia, la igualdad y el pluralismo político.\n2. La soberanía nacional reside en el pueblo español, del que emanan los poderes del Estado.\n3. La forma política del Estado español es la Monarquía parlamentaria.",
  "fechaVigenciaVersion": "1978-12-29",
  "fechaVigenciaHasta": null,
  "esVersionVigente": true,
  "numVersiones": 1,
  "estadoConsolidacion": "Finalizado",
  "materias": ["Constitución Española"],
  "urlEli": "https://www.boe.es/eli/es/c/1978/12/27/(1)",
  "urlHtml": "https://www.boe.es/buscar/act.php?id=BOE-A-1978-31229#a1",
  "hash": "9524cf9131d6ee9843c66a7aa2611828",
  "fuente": "Basado en datos de la Agencia Estatal Boletin Oficial del Estado (https://www.boe.es). Texto consolidado informativo, sin valor oficial."
}
```

#### Pricing (pay per event)

| Event | Price | Per 1,000 |
|---|---|---|
| Article extracted (`articulo`) | $0.001 | $1.00 |
| Law processed (`norma`) | $0.01 | $10.00 |

Example: the Spanish Constitution (about 170 articles) costs roughly $0.18. Set a maximum spend per run; the Actor stops and keeps what it saved.

#### Integrations (Make, Zapier, Google Sheets)

- **Make**: add the Apify module "Run an Actor" (Actor `Flets_sv/boe-legislacion-consolidada`), paste the input JSON, chain "Get Dataset Items" and map the fields to Google Sheets, Slack, Airtable or your CRM.
- **Zapier**: the Apify app offers "Run Actor" and "Fetch Dataset Items". Add a Schedule trigger and send each row to Gmail, Slack or Notion.
- **Google Sheets**: enable the official Google Sheets integration in the Actor's Integrations tab to append every run to a sheet, or call `https://api.apify.com/v2/acts/Flets_sv~boe-legislacion-consolidada/run-sync-get-dataset-items?format=csv` with POST and your input from Apps Script (`UrlFetchApp`).
- **API and webhooks**: start the Actor from the REST API, use Schedules for recurring runs and add a webhook to notify your system when a run finishes.

Input to paste into Make or Zapier:

```json
{"normas":["BOE-A-1978-31229"],"tiposBloque":["precepto"],"incluirHistorico":false,"soloCambios":false,"incluirMaterias":true,"formatoTexto":"texto","maxArticulos":1000,"pausaMs":500,"diasRetencion":365}
```

#### FAQ

**Is it legal?** Yes. The Actor uses the official open-data API of the BOE. Reuse of BOE information is permitted subject to citing the source (Law 37/2007 on reuse of public sector information). Every record includes `fuente`, `urlHtml` and `urlEli`. The consolidated text is informative and has no official value; only the BOE printed and electronic editions are authentic. This is not legal advice.

**How big laws behave?** The Civil Code has about 2,000 articles and takes several minutes because the Actor pauses politely between requests.

**Is the text in English?** No, the source is in Spanish. Use your LLM to translate on the fly.

**How do I detect amendments?** Schedule the Actor with `soloCambios: true`; the `cambio` and `hash` fields show what changed.

#### Integrations

- **API / SDKs:** `POST https://api.apify.com/v2/acts/flets_sv~boe-legislacion-consolidada/runs` or the JavaScript and Python clients.
- **Vector databases and RAG:** Apify integrations for Pinecone, Qdrant, Weaviate, LangChain and LlamaIndex consume the dataset directly.
- **Make, Zapier, n8n:** run on schedule and notify when a law changes.
- **MCP / AI agents:** expose it to Claude or any MCP client through `https://mcp.apify.com`.

#### Data source and license

Agencia Estatal Boletín Oficial del Estado (boe.es), open-data API. Independent Actor, not affiliated with the BOE.

***

### Español

#### ¿Qué hace?

Descarga la **legislación consolidada del BOE** desde su API oficial de datos abiertos y la entrega artículo a artículo: texto limpio, ruta jerárquica (título, capítulo, sección), fechas de vigencia, historial de versiones, materias, enlaces oficiales y hash de contenido. Ideal para **RAG jurídico**, vigilancia legislativa y cumplimiento normativo.

#### Input

Con `{}` devuelve los 20 primeros artículos de la Constitución. Campos: `normas` (ids BOE o URLs), `codigosPredefinidos` (Constitución, Código Civil, Código Penal, Estatuto de los Trabajadores, LEC, LGT, IVA, IRPF, LSC, Ley 39/2015, LCSP, LOPDGDD, LAU...), `tiposBloque`, `fechaVigencia`, `incluirHistorico`, `soloCambios`, `formatoTexto` y `maxArticulos`.

#### Output

Ver el ejemplo real de la sección inglesa.

#### Precios (pago por evento)

| Evento | Precio | Por 1.000 |
|---|---|---|
| Artículo extraído (`articulo`) | 0,001 $ | 1,00 $ |
| Norma procesada (`norma`) | 0,01 $ | 10,00 $ |

Puedes fijar un gasto máximo por ejecución.

#### Integraciones (Make, Zapier, Google Sheets)

- **Make**: añade el módulo de Apify «Run an Actor» (Actor `Flets_sv/boe-legislacion-consolidada`), pega el input JSON y encadena «Get Dataset Items»; después mapea los campos a Google Sheets, Slack, Airtable o tu CRM.
- **Zapier**: la app de Apify ofrece «Run Actor» y «Fetch Dataset Items». Ponle un disparador de horario y envía cada fila a Gmail, Slack o Notion.
- **Google Sheets**: en la pestaña Integrations del Actor activa la integración oficial con Google Sheets para añadir cada ejecución a una hoja, o llama desde Apps Script (`UrlFetchApp`) a `https://api.apify.com/v2/acts/Flets_sv~boe-legislacion-consolidada/run-sync-get-dataset-items?format=csv` con POST y tu input.
- **API y webhooks**: lanza el Actor por API REST, programa ejecuciones (Schedules) y avisa a tu sistema con un webhook al terminar.

Ejemplo de input para pegar en Make o Zapier:

```json
{"normas":["BOE-A-1978-31229"],"tiposBloque":["precepto"],"incluirHistorico":false,"soloCambios":false,"incluirMaterias":true,"formatoTexto":"texto","maxArticulos":1000,"pausaMs":500,"diasRetencion":365}
```

#### Preguntas frecuentes

**¿Es legal?** Sí: usa la API oficial de datos abiertos del BOE. La reutilización exige citar la fuente (Ley 37/2007); cada registro incluye `fuente`, `urlHtml` y `urlEli`. El texto consolidado es informativo y carece de valor oficial. No es asesoramiento jurídico.

**¿Cómo vigilo cambios?** Programa el Actor con `soloCambios` y usa `cambio` y `hash`.

#### Integración

API de Apify, Make, Zapier, n8n, bases vectoriales (Pinecone, Qdrant, LangChain, LlamaIndex) y agentes de IA vía MCP (`https://mcp.apify.com`).

#### Fuente y licencia

Agencia Estatal Boletín Oficial del Estado (boe.es). Actor independiente, sin afiliación con el BOE.

### Ejemplos de uso / Usage examples

#### Example output (real run, 2026-11-05)

First rows returned by a real run of this Actor on 2026-11-05 (shortened columns, values truncated):

| idNorma | tituloBloque | tipoBloque | fechaVigenciaVersion | texto |
|---|---|---|---|---|
| BOE-A-1992-28740 | Artículo 1 | precepto | 1993-01-01 | El Impuesto sobre el Valor Añadido es un tributo de natur... |
| BOE-A-1992-28740 | Artículo 2 | precepto | 1993-01-01 | Uno. El impuesto se exigirá de acuerdo con lo establecido... |
| BOE-A-1992-28740 | Artículo 3 | precepto | 2020-02-06 | Uno. El ámbito espacial de aplicación del impuesto es el... |

#### Copy-paste inputs

**1. Spanish VAT law as Markdown for a RAG index**

```json
{
  "codigosPredefinidos": [
    "ley-iva"
  ],
  "formatoTexto": "markdown",
  "maxArticulos": 500
}
```

**2. Labour and company law, only articles changed since the last run**

```json
{
  "codigosPredefinidos": [
    "estatuto-trabajadores",
    "ley-sociedades-capital"
  ],
  "soloCambios": true,
  "maxArticulos": 1000
}
```

#### Call it from your code (Apify API)

```bash
curl -X POST "https://api.apify.com/v2/acts/Flets_sv~boe-legislacion-consolidada/run-sync-get-dataset-items?token=YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"codigosPredefinidos": ["ley-iva"], "formatoTexto": "markdown", "maxArticulos": 500}'
```

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_API_TOKEN")
run = client.actor("Flets_sv/boe-legislacion-consolidada").call(run_input={"codigosPredefinidos": ["ley-iva"], "formatoTexto": "markdown", "maxArticulos": 500})
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)
```

No code? Use the Apify modules for **Make** and **Zapier** (run the Actor, then fetch dataset items), or the **Google Sheets** integration in the Actor's Integrations tab to append each run to a sheet.

# Actor input Schema

## `normas` (type: `array`):

Identificadores BOE (por ejemplo BOE-A-1978-31229) o URLs de boe.es de la norma consolidada.

## `codigosPredefinidos` (type: `array`):

Atajos a las normas mas consultadas: Constitucion, Codigo Civil, Codigo Penal y otras.

## `tiposBloque` (type: `array`):

Tipos de bloque a emitir: precepto (articulos), encabezado, parte_dispositiva o firma.

## `fechaVigencia` (type: `string`):

Si se indica, devuelve la version vigente en esa fecha. Vacio: version actual.

## `incluirHistorico` (type: `boolean`):

Emite todas las versiones de cada articulo, no solo una.

## `soloCambios` (type: `boolean`):

Emite solo los articulos nuevos o modificados desde la ultima ejecucion.

## `incluirMaterias` (type: `boolean`):

Anade las materias del analisis oficial de la norma a cada registro.

## `formatoTexto` (type: `string`):

Formato del campo texto: texto plano, markdown o html.

## `maxArticulos` (type: `integer`):

Tope de registros emitidos en total, para controlar el coste.

## `pausaMs` (type: `integer`):

Milisegundos de espera entre peticiones al BOE.

## `diasRetencion` (type: `integer`):

Dias que se conserva el estado de articulos vistos para detectar cambios.

## Actor input object example

```json
{
  "normas": [
    "BOE-A-1978-31229"
  ],
  "codigosPredefinidos": [],
  "tiposBloque": [
    "precepto"
  ],
  "fechaVigencia": "",
  "incluirHistorico": false,
  "soloCambios": false,
  "incluirMaterias": true,
  "formatoTexto": "texto",
  "maxArticulos": 1000,
  "pausaMs": 500,
  "diasRetencion": 365
}
```

# Actor output Schema

## `articulos` (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 = {
    "normas": [
        "BOE-A-1978-31229"
    ],
    "tiposBloque": [
        "precepto"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("flets_sv/boe-legislacion-consolidada").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 = {
    "normas": ["BOE-A-1978-31229"],
    "tiposBloque": ["precepto"],
}

# Run the Actor and wait for it to finish
run = client.actor("flets_sv/boe-legislacion-consolidada").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 '{
  "normas": [
    "BOE-A-1978-31229"
  ],
  "tiposBloque": [
    "precepto"
  ]
}' |
apify call flets_sv/boe-legislacion-consolidada --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,flets_sv/boe-legislacion-consolidada"
        }
    }
}
```

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/BvrF6XCwzrSMHdV0T/builds/FY06EOk0apoqYSOfE/openapi.json
