Skip to main content

10 - LegalTech Data Integration Patterns

An ECLI identifies a judgment across Europe: how to validate it, query EUR-Lex via SPARQL, normalise texts and protect the pipeline from outages.

What do you think about this article?

At a Glance

An ECLI identifies a judgment across Europe: how to validate it, query EUR-Lex via SPARQL, normalise texts and protect the pipeline from outages.

LegalTech data integration patterns: ECLI, SPARQL and pipelines that do not break

The same judgment reaches your system from three places: from the court's website, from a legal publisher and from a European database. Each calls it differently, with a different number, and none tells you that they are the same decision. If you do not solve this problem first, the search engine you build on top will show the same document three times and the assistant will cite the same source three times. Legal data integration is, first of all, a matter of identifiers and normalisation, and only afterwards of APIs.

This article takes the four pieces needed for a reliable ingestion and tests them with code that was run: a validity check on the European Case Law Identifier (ECLI), a client for the SPARQL endpoint of the Publications Office of the European Union, the normalisation of texts with the detection of changes, and resilience towards sources that sometimes do not answer. The data we talk about feeds the search engine, the Legal Copilot and the e-discovery platform.

ECLI: a key that is valid across Europe

The European Case Law Identifier was introduced by the conclusions of the Council of the European Union of 2011 (document 2011/C 127/01), which define its format in annex 1. An ECLI has five elements separated by colons, in this order: the abbreviation "ECLI", the country code, the code of the court, the year of the decision and an ordinal number. As a verifiable example, the judgment of the Court of Justice of 16 July 2020 in the Schrems II case has the identifier ECLI:EU:C:2020:559: country "EU", court "C" (the Court of Justice), year 2020, number 559.

The rules that matter for a validator are few and precise. The country code has two letters. The court code has from one to seven characters, starts with a letter and may contain digits. The year has four digits. The ordinal number is at most 25 characters long and may contain dots but no other punctuation. Only Latin alphanumeric characters are allowed and upper or lower case makes no difference. The listing translates them into a single regular expression and tries eleven strings: six are real ECLIs, taken from the European endpoint, and five are broken in different ways. Two practical details. I use fullmatch and not match with $, because in Python the $ also accepts a trailing newline. And the ordinal number is a string, not an integer: the one of the Italian Court of Cassation in the sample is 1209CIV, with a suffix in letters.

ecli.py - ECLI validator according to annex 1 of the conclusions 2011/C 127/01
import re
from dataclasses import dataclass

# Rules of annex 1 of the Council conclusions 2011/C 127/01:
#  - five elements separated by colons: ECLI : country : court : year : ordinal number
#  - country: two letters (for international organisations, codes that start with X)
#  - court: 1 to 7 characters, starts with a letter, may contain digits
#  - year: four digits
#  - ordinal number: at most 25 characters, may contain dots but no other punctuation
#  - only Latin alphanumeric characters; upper and lower case make no difference
ECLI_RE = re.compile(r"ECLI:([A-Z]{2}):([A-Z][A-Z0-9]{0,6}):(\d{4}):([A-Z0-9.]{1,25})")


@dataclass(frozen=True)
class Ecli:
    paese: str
    organo: str
    anno: int
    numero: str

    def __str__(self) -> str:
        return f"ECLI:{self.paese}:{self.organo}:{self.anno}:{self.numero}"


def leggi_ecli(testo: str) -> Ecli | None:
    """None if the form does not respect the specification. It does not say whether the ECLI EXISTS."""
    m = ECLI_RE.fullmatch(testo.strip().upper())
    if m is None:
        return None
    paese, organo, anno, numero = m.groups()
    return Ecli(paese, organo, int(anno), numero)


if __name__ == "__main__":
    campioni = [
        "ECLI:EU:C:2020:559",                     # Court of Justice
        "ECLI:EU:T:2020:131",                     # General Court of the EU
        "ECLI:IT:CASS:2000:1209CIV",              # Italian Court of Cassation: the number has a suffix
        "ECLI:AT:OGH0002:2001:RS0115274",         # court code with digits (7 characters)
        "ECLI:CZ:NS:2009:20.CDO.4032.2007.1",     # number with dots
        "ecli:eu:c:2020:559",                     # lower case: allowed, it is normalised
        "ECLI:EU:C:2020",                         # the number is missing
        "ECLI:EU:C:20:559",                       # two-digit year
        "ECLI:EU:CORTE_GIUST:2020:559",           # 11-character court code with an underscore
        "ECLI:EU:C:2020:559 OR 1=1",              # spaces: not an ECLI
        "ECLI:EU:C:2020:" + "1" * 26,             # 26-character number
    ]
    for c in campioni:
        e = leggi_ecli(c)
        print(("OK    " if e else "REJECT"), c[:44], "->", e)

# Output:
# OK     ECLI:EU:C:2020:559 -> ECLI:EU:C:2020:559
# OK     ECLI:EU:T:2020:131 -> ECLI:EU:T:2020:131
# OK     ECLI:IT:CASS:2000:1209CIV -> ECLI:IT:CASS:2000:1209CIV
# OK     ECLI:AT:OGH0002:2001:RS0115274 -> ECLI:AT:OGH0002:2001:RS0115274
# OK     ECLI:CZ:NS:2009:20.CDO.4032.2007.1 -> ECLI:CZ:NS:2009:20.CDO.4032.2007.1
# OK     ecli:eu:c:2020:559 -> ECLI:EU:C:2020:559
# REJECT ECLI:EU:C:2020 -> None
# REJECT ECLI:EU:C:20:559 -> None
# REJECT ECLI:EU:CORTE_GIUST:2020:559 -> None
# REJECT ECLI:EU:C:2020:559 OR 1=1 -> None
# REJECT ECLI:EU:C:2020:11111111111111111111111111 -> None

The output separates the cases. The first five are accepted and you see how much the ordinal number varies: a plain digit string for the Court of Justice, a subject suffix for the Cassation, a code with letters and digits for the Austrian OGH, dots for the Czech court. Lower case is accepted and normalised. The last lines are the rejections: missing number, two-digit year, a court code that is too long and has an underscore, a space with an added clause, a 26-character number. Mind the limit of this check: it says whether the form is right, not whether the judgment exists. The only way to know is to ask the source, and that is the next step. A curiosity of the text: in the Italian version of the conclusions the code of the European Union is written "UE", while the identifiers the endpoint returns use EU; for a validator, what counts is the format the data really use.

Querying EUR-Lex: a SPARQL endpoint, and a pitfall

The Publications Office of the European Union exposes the metadata of EUR-Lex as linked data, queryable with SPARQL at the address https://publications.europa.eu/webapi/rdf/sparql. The SPARQL 1.1 protocol provides for sending the query with a POST whose parameters are encoded like a form (section 2.1.2 of the protocol), which is what the listing does with the standard library. I tried the endpoint on 12 November 2026 without a key or registration.

The pitfall is injection. The query contains the ECLI, and if you paste it into the string without checking it, a crafted value can change the query: as in SQL injection, only with another language. Here the defence is already written: the validator above accepts only alphanumeric characters and dots, so any attempt with quotation marks, brackets or spaces is rejected before it reaches the query. The braces of the query are doubled because the string goes through str.format: forgetting it produces a KeyError, not a SPARQL error. The other choice to note is the selection in the English language, with cdm:expression_uses_language: without it, you get a title for every language.

eurlex.py - search for a judgment by ECLI on the Publications Office endpoint
import json
import urllib.parse
import urllib.request

from ecli import leggi_ecli

ENDPOINT = "https://publications.europa.eu/webapi/rdf/sparql"
ENG = "http://publications.europa.eu/resource/authority/language/ENG"

QUERY = """PREFIX cdm: <http://publications.europa.eu/ontology/cdm#>
SELECT ?celex ?data ?titolo WHERE {{
  ?opera cdm:case-law_ecli "{ecli}"^^<http://www.w3.org/2001/XMLSchema#string> ;
         cdm:resource_legal_id_celex ?celex ;
         cdm:work_date_document ?data .
  ?espressione cdm:expression_belongs_to_work ?opera ;
               cdm:expression_uses_language <{lingua}> ;
               cdm:expression_title ?titolo .
}} LIMIT 20"""


def cerca_per_ecli(testo_ecli: str, timeout: float = 60.0) -> list[dict]:
    ecli = leggi_ecli(testo_ecli)
    if ecli is None:                      # validation IS the defence against SPARQL injection
        raise ValueError(f"Invalid ECLI: {testo_ecli!r}")
    query = QUERY.format(ecli=ecli, lingua=ENG)
    richiesta = urllib.request.Request(
        ENDPOINT,
        data=urllib.parse.urlencode({"query": query}).encode(),
        headers={"Accept": "application/sparql-results+json"},
    )
    with urllib.request.urlopen(richiesta, timeout=timeout) as risposta:
        righe = json.load(risposta)["results"]["bindings"]
    return [{k: v["value"] for k, v in riga.items()} for riga in righe]


if __name__ == "__main__":
    righe = cerca_per_ecli("ECLI:EU:C:2020:559")
    per_celex = {}
    for r in righe:
        per_celex.setdefault(r["celex"], r)            # one entry per CELEX
    print("rows returned     :", len(righe))
    print("distinct CELEX    :", sorted(per_celex))
    d = per_celex["62018CJ0311"]
    print("date              :", d["data"])
    print("title (first two parts):", " / ".join(d["titolo"].split("#")[:2]))
    try:
        cerca_per_ecli('ECLI:EU:C:2020:559" } UNION { ?s ?p ?o')
    except ValueError as e:
        print("hostile input     :", e)

# Output:
# rows returned     : 3
# distinct CELEX    : ['62018CJ0311', '62018CJ0311_RES']
# date              : 2020-07-16
# title (first two parts): Judgment of the Court (Grand Chamber) of 16 July 2020. / Data Protection Commissioner v Facebook Ireland Limited and Maximillian Schrems.
# hostile input     : Invalid ECLI: 'ECLI:EU:C:2020:559" } UNION { ?s ?p ?o'

The result holds a surprise that explains why normalisation is needed. For a single ECLI the endpoint returns three rows, with two distinct CELEX numbers: 62018CJ0311 and 62018CJ0311_RES. The first number appears twice, with two English titles of different length. The second has a suffix that I have not investigated, and I will not tell you what it is: I tell you that, if you treat every row as a document, you duplicate the judgment. The rule is one entry per CELEX and an explicit decision on which to keep. The title arrives with its parts separated by the character #, which in the listing I show split, keeping only the first two parts (the third is a long chain of subject keywords). This output was obtained from the live service and may change: the number of rows depends on the data the Publications Office publishes at that moment. For the record, the Italian-language run of the same query returned two rows.

Normalising and noticing what has changed

A pipeline that compares texts must first make them comparable. The most insidious case is the accent: "autorità" (Italian for "authority") can be written with a single "à" or with an "a" followed by a combining accent, and the two texts are visually identical but have different bytes. The listing shows it, and shows the remedy: Unicode NFC normalisation, described in the documentation of unicodedata, which brings both to the composed form. In the same way the invisible soft hyphen and the non-breaking space must not trigger a "change".

To detect changes I chose the simplest road that works: at every round a fingerprint of the normalised text is computed for each document (truncated SHA-256, here only for comparison, not for security) and compared with the one from the previous round. The term "change data capture" in the strict sense concerns the transaction logs of a database that you control: for an external source that notifies you of nothing, what you can do is this periodic comparison.

normalizza.py - NFC normalisation and comparison between two snapshots
import hashlib
import re
import unicodedata
from dataclasses import dataclass


def normalizza_testo(testo: str) -> str:
    testo = unicodedata.normalize("NFC", testo)        # "e" + combining accent -> "è"
    testo = testo.replace("­", "")                 # invisible soft hyphen
    testo = testo.replace(" ", " ")                # non-breaking space
    testo = re.sub(r"[ \t]+", " ", testo)
    return testo.strip()


def titolo_leggibile(titolo_grezzo: str) -> str:
    """EUR-Lex separates the parts of the title with '#': we turn them into sentences."""
    parti = [normalizza_testo(p) for p in titolo_grezzo.split("#") if p.strip()]
    return " ".join(parti)


def impronta(testo: str) -> str:
    return hashlib.sha256(normalizza_testo(testo).encode("utf-8")).hexdigest()[:12]


@dataclass(frozen=True)
class Change:
    id: str
    kind: str        # "new", "modified", "gone"


def confronta(precedente: dict[str, str], attuale: dict[str, str]) -> list[Change]:
    """precedente and attuale map document id -> fingerprint of the normalised text."""
    esiti = []
    for id_, h in attuale.items():
        if id_ not in precedente:
            esiti.append(Change(id_, "new"))
        elif precedente[id_] != h:
            esiti.append(Change(id_, "modified"))
    esiti += [Change(i, "gone") for i in precedente if i not in attuale]
    return esiti


if __name__ == "__main__":
    composto = "autorità"             # 'à' in a single character
    scomposto = "autorità"           # 'a' + combining accent: same word, different bytes
    print("look equal     :", composto == scomposto, "| after NFC:",
          normalizza_testo(composto) == normalizza_testo(scomposto))
    print("title          :", titolo_leggibile("Judgment of 16 July 2020.#Case C-311/18.#Reference for a preliminary ruling"))

    ieri = {"A": impronta("Art. 1 text"), "B": impronta("Art. 2 text"), "C": impronta("Art. 3 text")}
    oggi = {"A": impronta("Art. 1 text"), "B": impronta("Art. 2 text modified"), "D": impronta("Art. 4 text")}
    for v in confronta(ieri, oggi):
        print(v)
    # The same text with a non-breaking space instead of a space is NOT a change:
    print("false alarm    :", impronta("Art. 1 text") == impronta("Art. 1 text"))

# Output:
# look equal     : False | after NFC: True
# title          : Judgment of 16 July 2020. Case C-311/18. Reference for a preliminary ruling
# Change(id='B', kind='modified')
# Change(id='D', kind='new')
# Change(id='C', kind='gone')
# false alarm    : True

The output has three things to look at. The first line confirms that the two spellings of "autorità" are different before and equal after NFC. The title loses the # separators and becomes readable. The comparison between the two snapshots finds exactly the three expected changes: B modified, D new, C gone. And the last line is the test that counts: a non-breaking space in place of a normal space does not produce a false alarm. Without normalising before computing the fingerprint, every invisible difference would generate a notification, and after the tenth useless notification nobody reads notifications any more.

Four rules for legislative data

These pieces sum up in four rules of discipline, more than of code:

  • Primary source: legislative texts are taken from the official portal (Normattiva for Italian laws, EUR-Lex for European ones), not from copies.
  • Versions: the history of a text is kept, not only the latest version, because a dispute is judged with the rule in force at the time of the facts.
  • Extraction date: next to the date of the document you record when you read it, so that you can reconstruct what the system knew on a given day.
  • Normalisation before comparison: everything is brought to a canonical form before computing fingerprints or duplicates.

The thread that ties them is reconstructability: after an error you must be able to say where the text came from, when you read it and which version it was. The first two rules protect correctness, the last two protect the ability to prove it. None is free: keeping versions and extraction dates costs space, and for this reason it is worth deciding at once how far back in time the product must be able to look.

Resilience: sources that do not answer

A public source may slow down, answer with errors or disappear for hours, and the pipeline must neither block nor hammer it. Two mechanisms cover the two cases. The first is retry with growing waits: an isolated network error is overcome by trying again after one second, then two, then four. The second is the circuit breaker: if the consecutive failures exceed a threshold, for a while the calls stop altogether, and then a single trial call is let through. The two combine, but with a warning: the retry must not insist on an open circuit.

The listing does not really wait: the clock and the wait function are parameters, so the behaviour is tested in an instant and with fixed times. Two things are deliberately missing that a real system adds, and I declare them so as not to leave the impression of finished code: a little randomness in the waits (jitter), to prevent many clients from all retrying in the same second, and respect for the rate limits that the source declares.

resilienza.py - retries with growing waits and circuit breaker
from dataclasses import dataclass, field
from typing import Callable


class CircuitoAperto(Exception):
    pass


@dataclass
class Interruttore:
    soglia: int = 3                 # consecutive failures before opening
    pausa: float = 120.0            # seconds to wait before a trial call
    orologio: Callable[[], float] = field(default=lambda: 0.0)
    fallimenti: int = 0
    aperto_dal: float | None = None

    def chiama(self, azione):
        if self.aperto_dal is not None:
            if self.orologio() - self.aperto_dal < self.pausa:
                raise CircuitoAperto("service suspended: not calling it")
            # pause expired: let ONE trial call through ("half-open" state)
        try:
            risultato = azione()
        except Exception:
            self.fallimenti += 1
            if self.fallimenti >= self.soglia or self.aperto_dal is not None:
                self.aperto_dal = self.orologio()
            raise
        self.fallimenti, self.aperto_dal = 0, None
        return risultato


def con_ripetizioni(azione, tentativi=3, attesa=1.0, fattore=2.0, dormi=lambda s: None):
    """Retries with growing waits: 1, 2, 4... seconds. 'dormi' (sleep) can be injected for tests."""
    for n in range(1, tentativi + 1):
        try:
            return azione()
        except CircuitoAperto:
            raise                                   # no point insisting on an open circuit
        except Exception as e:
            if n == tentativi:
                raise
            print(f"  attempt {n} failed ({e}); retrying in {attesa:g}s")
            dormi(attesa)
            attesa *= fattore


if __name__ == "__main__":
    adesso = [0.0]
    esiti_servizio = iter(["error", "error", "ok"])

    def servizio():
        e = next(esiti_servizio)
        if e == "error":
            raise ConnectionError("timeout")
        return "document"

    print("1) unstable service, 3 attempts:")
    print("  ->", con_ripetizioni(servizio))

    print("2) service down, threshold 3:")
    sempre_giu = lambda: (_ for _ in ()).throw(ConnectionError("down"))
    ib = Interruttore(orologio=lambda: adesso[0])
    for i in range(5):
        try:
            ib.chiama(sempre_giu)
        except CircuitoAperto as e:
            print(f"  call {i + 1}: {e}")
        except ConnectionError:
            print(f"  call {i + 1}: service error")
    adesso[0] = 121.0
    print("3) after 121 seconds, service back:", ib.chiama(lambda: "document"))

# Output:
# 1) unstable service, 3 attempts:
#   attempt 1 failed (timeout); retrying in 1s
#   attempt 2 failed (timeout); retrying in 2s
#   -> document
# 2) service down, threshold 3:
#   call 1: service error
#   call 2: service error
#   call 3: service error
#   call 4: service suspended: not calling it
#   call 5: service suspended: not calling it
# 3) after 121 seconds, service back: document

Case 1 shows the waits of 1 and 2 seconds before success on the third attempt. In case 2 the first three calls really fail, at the fourth the circuit breaker has opened and answers "service suspended" without touching the source, and the same at the fifth. Case 3 simulates that 121 seconds have passed, beyond the pause of 120: the circuit breaker lets a trial call through, the source is back, and the circuit closes again. The price of this scheme is that for two minutes the system works without fresh data: it must be decided, for each source, whether it is better to serve old data with their date or nothing.

What you can do now

You can identify a decision with an ECLI and validate its form, you can query the European SPARQL endpoint without opening the door to injection, you know that a single ECLI can correspond to several documents and therefore deduplication rules are needed, you can compare two snapshots of a corpus without false alarms, and you can prevent a stalled source from blocking the rest. What I have not verified, and what you will have to do for each source, is the format and the update frequency of each: every portal has its own terms of use, and they must be read before building an automatic process on top. The starting point of the series was contract analysis: the data these systems consume start here.

Next in the series: AI in Italian Justice: What the Law and the AI Act Allow.

Sources

The four listings were run with Python 3.14. The SPARQL client queried the real endpoint on 2026-11-12: the number of rows and the titles are those of that day and may change. I did not try Normattiva or the feeds of the Gazzetta Ufficiale, and I did not verify the codes of the Italian courts beyond the example of the Cassation found in the data.

Frequently asked questions

What is an ECLI and how is it made?

It is the European identifier of case law: five elements separated by colons (the abbreviation ECLI, the country, the court, the four-digit year and an ordinal number). An example is ECLI:EU:C:2020:559.

Does a valid ECLI always correspond to an existing judgment?

No. Validation checks only the form. To know whether the decision exists you must ask the source, for example the SPARQL endpoint of the Publications Office.

Why can the same ECLI return several documents?

Because the identifier points to the decision, not to a file. In the test with ECLI:EU:C:2020:559 the endpoint returned two distinct CELEX numbers, and the system must decide which one to keep and how to deduplicate.

What is the circuit breaker for, next to the retries?

Retries overcome isolated errors; the circuit breaker stops calling a stalled source after too many consecutive failures, so you do not hammer it and do not block the pipeline, and it lets a trial call through when the pause has expired.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects