Spanish Tax Rulings Scraper (DGT Binding Consultations)
Pricing
Pay per event
Spanish Tax Rulings Scraper (DGT Binding Consultations)
Search and export binding tax rulings from the Spanish Tax Directorate (DGT): full answer, facts, laws and articles cited. Monitor new rulings for advisors.
Search and export binding tax rulings (consultas vinculantes) from the Spanish Tax Directorate (DGT, Ministry of Finance): full answer text, facts, question, laws and articles cited. Monitor new rulings for tax advisors, law firms and legal AI. Versión en español más abajo.
English
What does it do?
The Actor queries the official DGT doctrine database (Petete) and returns each ruling as a structured record. Use it to build a searchable base of Spanish tax doctrine or to collect only the rulings you have not seen before.
- Tax advisory and gestorías: find how the DGT interprets a rule (VAT, IRPF, inheritance tax, corporate tax).
- Legal AI / RAG: feed full rulings with cited laws and articles into a retrieval pipeline.
- Monitoring: with
soloNuevasa scheduled run emits only rulings it has not emitted before. - Research: filter by date range, ruling type, free text, law, question or facts.
Input
Every field is optional. Fields are grouped in the Apify form as Que buscar, Fechas y tipo, Salida y coste and Vigilancia y ritmo.
| Field | Description |
|---|---|
textoLibre | Free-text search over the whole ruling. |
numeroConsulta | One ruling number, e.g. V1000-25 (V optional, up to 5 digits, hyphen, 2 digits). An invalid format makes the run fail before any request. |
normativa | Text that must appear in the cited legislation, e.g. Ley 37/1992. |
cuestionPlanteada, descripcionHechos | Text in the question or in the facts. |
fechaDesde / fechaHasta | Output date range, YYYY-MM-DD. Only fechaDesde: up to today. Only fechaHasta: from 1990-01-01. An invalid date, or fechaDesde after fechaHasta, fails the run. |
tipos | vinculantes and/or generales (default vinculantes). An empty list fails the run. |
soloCriterioInteres | Only rulings the DGT flags as "criterio de interés". |
incluirContestacion | Download the full answer (default true). If false, only list data is returned. |
maxResultados | Cap, 1 to 5000. The form default is 10; if the field is absent the code uses 100. |
soloNuevas | Skip rulings already emitted in earlier runs (see "How it works"). |
diasRetencion | Days a ruling stays remembered for soloNuevas (1 to 3650, default 365). |
pausaMs | Wait between requests to the source, 500 to 10000 ms (default 1000). |
resumenIA | Optional AI summary per ruling, off by default (see FAQ). |
With no filter at all ({}) the Actor searches the last 30 days and, if the source returns nothing, widens to 90, 180 and 365 days. It returns at most 10 rulings in that case.
Two ready inputs (illustrative, not tied to a specific run):
{ "textoLibre": "donaciones", "fechaDesde": "2026-01-01", "maxResultados": 25 }
{ "normativa": "Ley 37/1992", "fechaDesde": "2025-10-01", "fechaHasta": "2025-10-31", "tipos": ["vinculantes"], "maxResultados": 25, "soloNuevas": true }
How it works (and what is retried)
- It opens a session on Petete and posts the search form, one results page at a time, then (if
incluirContestacionis on) one request per ruling for the full document. Rulings repeated in the results and rulings marked as annulled (anulada) are skipped. - Retried: network errors, HTTP 429 and HTTP 5xx on a request are retried up to 4 times (5 requests in total) with a wait that doubles from 2 s. Opening the session is retried up to 5 times for the same kinds of failure. An HTTP 401 renews the session once and repeats the request.
- Not retried: any other HTTP error (for example 403 or 404), a second 401 after renewing, and an invalid input. Invalid input makes the run fail with "Entrada no valida".
- When a ruling cannot be read: a failed document read is counted as an error and skipped; after 3 failed reads in a row the run stops. A document that cannot be parsed is skipped and counted as an error. If the search breaks after some rulings were saved, the run ends with those results and a warning; if it breaks before the first one, the run fails.
soloNuevas: the Actor keeps the numbers of emitted rulings in its key-value store (ESTADO_DEDUPE) fordiasRetenciondays. Rulings are remembered only after they were saved.- Spend limit: if you set a maximum cost per run, the Actor stops when the limit is reached and keeps what it saved. When the run finishes normally (
ejecutar()returns,src/main.ts) it also writes aRESUMENrecord (emitted, charged, skipped, errors, warnings) to the key-value store; if the run fails with an error, noRESUMENis written.
Code: input src/entrada.ts (normalizarEntrada), dates src/filtros/fechas.ts (rangoBuscador), requests and retries src/fuente/petete.ts (ClientePetete), main loop and errors src/ejecutar.ts (ejecutar), charging src/cobro.ts (crearCobrador), state src/estado/dedupe.ts.
Output
ILLUSTRATIVE item: shortened and with example values, not the result of a specific run. Field names and types are those of the Consulta interface (src/dominio/consulta.ts), filled in by ejecutar() (src/ejecutar.ts); hash is the SHA-256 (64 hex characters) computed by huella() over number, date, question and answer; idDocumento is a number.
{"tipo": "vinculante","numeroConsulta": "V5441-26","organo": "SG de Impuestos Patrimoniales, Tasas y Precios Públicos","fechaSalida": "2026-08-06","normativa": "Ley 29/1987 Impuesto sobre Sucesiones y Donaciones - 3.1 - 5 - 6.1 ...","leyesCitadas": ["Ley 29/1987", "RD 1629/1991", "Ley 22/2009"],"articulosCitados": ["3.1", "5", "6.1", "6.2", "9"],"descripcionHechos": "El consultante va a recibir de sus padres transferencias de dinero de forma periódica...","cuestionPlanteada": "Tributación de las transferencias periódicas en el Impuesto sobre Sucesiones y Donaciones.","contestacion": "En relación con las cuestiones planteadas este Centro Directivo informa lo siguiente: ...","longitudContestacion": 8026,"criterioInteres": null,"idDocumento": 70284,"urlBuscador": "https://petete.tributos.hacienda.gob.es/consultas/","fuente": "Ministerio de Hacienda - Direccion General de Tributos (petete.tributos.hacienda.gob.es). No es asesoramiento fiscal.","extraidoEn": "2026-10-31T18:10:45.020Z","hash": "726ef56f1b490badbe684791e4a52c5fe89ebd176b4fef10cbf80116de501519"}
Notes: with incluirContestacion: false, organo, fechaSalida and normativa are null, the lists are empty and contestacion is null (only number, facts and question come from the results list). criterioInteres is true only when you filtered by soloCriterioInteres, otherwise null. resumenIA appears only when a summary was produced.
Pricing (pay per event)
Events charged: ruling with full answer (consulta), ruling with list data only (consulta-metadatos) and AI summary (resumen-ia, optional). Current prices are shown on the Pricing tab of the Actor page on Apify.
The ruling event is charged for each ruling right before it is saved. An empty input returns at most 10 rulings.
Integrations (Make, Zapier, Google Sheets)
- Make: add the Apify module "Run an Actor" (Actor
Flets_sv/dgt-consultas-vinculantes), 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, or call
https://api.apify.com/v2/acts/Flets_sv~dgt-consultas-vinculantes/run-sync-get-dataset-items?format=csvwith POST and your input from Apps Script (UrlFetchApp). - API and webhooks: start the Actor from the REST API, use Schedules for recurring runs and a webhook to notify your system when a run finishes.
Python:
from apify_client import ApifyClientclient = ApifyClient("YOUR_API_TOKEN")run = client.actor("Flets_sv/dgt-consultas-vinculantes").call(run_input={"textoLibre": "donaciones", "fechaDesde": "2026-01-01", "maxResultados": 25})for item in client.dataset(run["defaultDatasetId"]).iterate_items():print(item["numeroConsulta"], item["fechaSalida"])
FAQ
Is it legal? The rulings are public administrative doctrine published by the Ministry of Finance. Reuse is allowed under Law 37/2007 on reuse of public sector information; cite the source (each record has fuente). The Actor pauses between requests (pausaMs). This is not tax or legal advice.
Do I get the full answer? Yes, by default. Turn off incluirContestacion for a cheaper list.
Binding vs general? Binding rulings (V...) bind the tax administration in the case; general ones are informative. Choose with tipos.
Is it in English? The source is in Spanish. resumenIA only works if the Actor has an AI gateway configured; otherwise the option is ignored, a warning is added to RESUMEN and no resumen-ia event is charged. Use your own LLM to translate.
Why did a run return fewer rulings than found? maxResultados, a spend limit, annulled rulings, repeated rulings or soloNuevas all reduce the output. The counts are in the RESUMEN record.
Data source and license
Ministerio de Hacienda, Dirección General de Tributos (petete.tributos.hacienda.gob.es). Independent Actor, not affiliated with the Spanish administration.
Español
¿Qué hace?
Busca en la base oficial de doctrina de la Dirección General de Tributos (Petete) y devuelve cada consulta como registro estructurado: órgano, fecha, hechos, cuestión planteada, contestación completa, leyes y artículos citados. Pensado para asesorías fiscales, gestorías, despachos de abogados y proyectos de IA jurídica.
Input
Todos los campos son opcionales; en el formulario van agrupados en Que buscar, Fechas y tipo, Salida y coste y Vigilancia y ritmo.
| Campo | Descripción |
|---|---|
textoLibre | Texto libre en toda la consulta. |
numeroConsulta | Un número, p. ej. V1000-25 (V opcional, hasta 5 cifras, guion, 2 cifras). Si el formato no es válido, la ejecución falla antes de pedir nada. |
normativa | Texto que debe aparecer en la normativa citada, p. ej. Ley 37/1992. |
cuestionPlanteada, descripcionHechos | Texto en la cuestión o en los hechos. |
fechaDesde / fechaHasta | Fecha de salida, AAAA-MM-DD. Solo fechaDesde: hasta hoy. Solo fechaHasta: desde 1990-01-01. Fecha inválida o fechaDesde posterior a fechaHasta: falla. |
tipos | vinculantes y/o generales (por defecto vinculantes). Lista vacía: falla. |
soloCriterioInteres | Solo las marcadas por la DGT como criterio de interés. |
incluirContestacion | Descarga la contestación completa (por defecto sí). Si no, solo datos de la lista. |
maxResultados | Tope de 1 a 5000. En el formulario vale 10; si el campo no llega, el código usa 100. |
soloNuevas | Omite las consultas ya emitidas en ejecuciones anteriores. |
diasRetencion | Días que se recuerda una consulta para soloNuevas (1 a 3650, por defecto 365). |
pausaMs | Espera entre peticiones a la fuente, 500 a 10000 ms (por defecto 1000). |
resumenIA | Resumen con IA opcional, desactivado por defecto (ver preguntas frecuentes). |
Sin ningún filtro ({}) busca los últimos 30 días y, si la fuente no devuelve nada, amplía a 90, 180 y 365 días; en ese caso devuelve como máximo 10 consultas.
Dos entradas listas para pegar (ilustrativas, no salen de una ejecución concreta):
{ "textoLibre": "donaciones", "fechaDesde": "2026-01-01", "maxResultados": 25 }
{ "normativa": "Ley 37/1992", "fechaDesde": "2025-10-01", "fechaHasta": "2025-10-31", "tipos": ["vinculantes"], "maxResultados": 25, "soloNuevas": true }
Cómo funciona (y qué se reintenta)
- Abre sesión en Petete y envía la búsqueda página a página; con
incluirContestacionactivo pide además un documento por consulta. Se omiten las consultas repetidas en los resultados y las anuladas. - Se reintenta: errores de red, HTTP 429 y HTTP 5xx, hasta 4 reintentos (5 peticiones en total) con espera que se duplica desde 2 s. La apertura de sesión se reintenta hasta 5 veces por los mismos fallos. Un HTTP 401 renueva la sesión una vez y repite la petición.
- No se reintenta: cualquier otro error HTTP (403, 404...), un segundo 401 tras renovar y la entrada no válida, que termina la ejecución con «Entrada no valida».
- Si una consulta no se puede leer: se cuenta como error y se salta; con 3 lecturas fallidas seguidas la ejecución se detiene. Un documento que no se puede interpretar se salta y se cuenta como error. Si la búsqueda se rompe después de guardar algunas consultas, termina con ellas y un aviso; si se rompe antes de la primera, falla.
soloNuevas: guarda los números emitidos en el almacén clave-valor (ESTADO_DEDUPE) durantediasRetenciondías, y solo tras guardarlos.- Tope de gasto: si fijas un coste máximo por ejecución, se detiene al alcanzarlo y conserva lo guardado. Si la ejecución termina con normalidad (
ejecutar()devuelve el resultado,src/main.ts) escribe además un registroRESUMEN(emitidas, cobradas, omitidas, errores, avisos); si la ejecución falla con un error, no se escribeRESUMEN.
Código: src/entrada.ts, src/filtros/fechas.ts, src/fuente/petete.ts, src/ejecutar.ts, src/cobro.ts, src/estado/dedupe.ts.
Output
Ver el ejemplo ILUSTRATIVO de la sección inglesa (valores de ejemplo, no de una ejecución concreta; los nombres y tipos de los campos son los de Consulta en src/dominio/consulta.ts, rellenados por ejecutar() en src/ejecutar.ts; hash es el SHA-256 de 64 caracteres hexadecimales que calcula huella() y idDocumento es un número). Con incluirContestacion desactivado, organo, fechaSalida, normativa y contestacion salen en null y las listas vacías. criterioInteres es true solo si filtraste por soloCriterioInteres; si no, null.
Precios (pago por evento)
Eventos que se cobran: consulta con contestación (consulta), consulta solo con la lista (consulta-metadatos) y resumen con IA (resumen-ia, opcional). Los precios vigentes están en la pestaña de precios de la ficha del Actor en Apify.
El evento de consulta se cobra por cada una justo antes de guardarla. Con entrada vacía, máximo 10 consultas.
Integraciones (Make, Zapier, Google Sheets)
- Make: módulo de Apify «Run an Actor» (Actor
Flets_sv/dgt-consultas-vinculantes), pega el input y encadena «Get Dataset Items» hacia Google Sheets, Slack, Airtable o tu CRM. - Zapier: la app de Apify ofrece «Run Actor» y «Fetch Dataset Items»; añade un disparador de horario.
- Google Sheets: integración oficial en la pestaña Integrations del Actor, o
UrlFetchAppdesde Apps Script contrahttps://api.apify.com/v2/acts/Flets_sv~dgt-consultas-vinculantes/run-sync-get-dataset-items?format=csvcon POST. - API y webhooks: lanza el Actor por API REST, programa ejecuciones (Schedules) y avisa a tu sistema con un webhook.
Preguntas frecuentes
¿Es legal? Es doctrina administrativa pública del Ministerio de Hacienda, reutilizable según la Ley 37/2007; cita la fuente (fuente en cada registro). El Actor espera entre peticiones (pausaMs). No es asesoramiento fiscal ni jurídico.
¿Cómo recibo solo las nuevas? Programa el Actor con soloNuevas activado; la primera ejecución las emite todas.
¿Y el resumen con IA? Solo funciona si el Actor tiene una pasarela de IA configurada; si no, se ignora, se añade un aviso a RESUMEN y no se cobra resumen-ia.
¿Por qué salen menos consultas de las encontradas? Lo explican maxResultados, el tope de gasto, las anuladas, las repetidas y soloNuevas; los contadores están en RESUMEN.
Fuente y licencia
Ministerio de Hacienda, Dirección General de Tributos. Actor independiente, sin afiliación con la Administración.