Article

API Contracts and Versioning: Preventing Regressions in Judicial Publication Monitoring

15 min read

A practical framework for defining API contracts, testing changes, and rolling out new versions without interrupting deadlines, feeds, or connected ERPs.

Explore a safer integration approach
API Contracts and Versioning: Preventing Regressions in Judicial Publication Monitoring

API contract versioning is the discipline of defining how systems exchange data and controlling how those rules change over time. In a legal operation, the contract may describe the fields, data types, required values, event order, authentication behavior, and error responses used to deliver a judicial publication to an ERP, CRM, process manager, or internal dashboard.

The risk is easy to underestimate. A developer may rename numero_processo to process_number because the new name appears clearer, while an internal workflow still uses the original field to identify the case. The API may remain technically available, but deadline extraction, assignment, or notification can silently stop working.

Legal publication data also carries operational consequences. If data_publicacao changes from a date to a timestamp, or if confianca_extracao changes from a decimal between 0 and 1 to a percentage between 0 and 100, downstream rules can produce incorrect urgency levels without generating a visible error.

A useful contract therefore covers more than an endpoint URL. It documents the meaning of each field, whether it can be null, its format, permitted values, uniqueness rules, pagination behavior, retry expectations, and the conditions under which a consumer can rely on the data.

The OpenAPI specification provides a widely used structure for documenting HTTP APIs, but documentation alone does not prevent regressions. The contract must also be tested against real consumer expectations before a change reaches production.

How to model a judicial publication API contract

Start with a canonical publication model that represents the business event rather than the database behind it. A simple example might include id_publicacao, numero_processo, data_publicacao, tribunal, instancia, texto_original, resumo, confianca_extracao, and documentos.

For example, a response could be represented as {"id_publicacao":"pub_78421","numero_processo":"0001234-56.2026.8.26.0100","data_publicacao":"2026-10-27","tribunal":"TJSP","instancia":"1","confianca_extracao":0.96,"resumo":"Intimação para manifestação","documentos":[]}. The exact payload will vary, but each property should have an explicit semantic definition.

Field mapping is essential when the consumer uses different names. An ERP might map numero_processo to case_id, data_publicacao to publication_date, and confianca_extracao to extraction_score. Store that mapping in version control, review it like application code, and test it with representative payloads.

Do not use a field name as a substitute for a business definition. data_publicacao should specify whether it means the date shown in the official publication, the date captured by the monitoring service, or the date delivered to the consumer. These dates can differ, and the distinction matters when a legal team calculates response windows.

The contract should also distinguish facts from interpretations. texto_original is source content, while resumo, prazo_estimado, and acao_sugerida may be generated or extracted values. Consumers should be able to identify which fields came from the source and which require human validation.

For AI-enabled workflows, define whether a model-generated summary is optional, how its confidence is represented, and what happens when extraction fails. A missing summary should not prevent the original publication from reaching the legal team, especially when the publication may contain a deadline.

  1. 1

    Classify the proposed change

    Separate additive changes from breaking changes. Adding an optional response field is usually compatible, while renaming a field, changing its type, removing an enum value, or altering date semantics requires a stronger migration plan.

  2. 2

    Assign an explicit contract version

    Use a clear policy such as /v1 and /v2, a versioned media type, or a documented event schema version. The important point is consistency: every consumer must be able to identify which rules apply to a payload.

  3. 3

    Introduce compatibility before migration

    When possible, publish the new field while preserving the old one. For example, expose publication_date alongside data_publicacao, document both, and measure which consumers have migrated before removing the legacy field.

  4. 4

    Test actual consumer behavior

    Validate not only whether a payload matches the schema, but also whether the ERP creates the correct task, the process manager preserves the case number, and the notification rule recognizes the publication date.

  5. 5

    Announce a deprecation window

    Set a date, migration guide, owner, and support channel for every breaking change. A legal department with several outsourced firms or ERPs needs enough time to coordinate changes across organizations.

  6. 6

    Roll out gradually

    Use a canary consumer, tenant-level feature flag, or parallel delivery path before broad activation. Compare event counts, field completeness, processing latency, and downstream task creation during the overlap period.

  7. 7

    Remove the old contract only with evidence

    Retire a version after logs and consumer acknowledgments show that active integrations have migrated. Keep an audit record of the final payloads, migration date, and rollback procedure.

Which automated tests should run before changing a publication field?

  • ✓Schema validation tests confirm required properties, data types, formats, nullable behavior, and nested structures. Include valid and invalid examples for process numbers, publication dates, confidence scores, documents, and tribunal identifiers.
  • ✓Consumer-driven contract tests verify the expectations of each ERP, CRM, process manager, or internal service. A consumer should publish its assumptions, such as requiring numero_processo and accepting an optional resumo, so the provider can test against them before deployment.
  • ✓Field-mapping tests detect semantic regressions. Assert that a process number remains unchanged through transformation, that a date preserves its timezone and meaning, and that confianca_extracao is not silently converted from 0.96 to 96 or vice versa.
  • ✓Fixture tests use anonymized publication examples from different courts, instances, document types, and text patterns. Include mocks for missing documents, duplicate events, delayed publication dates, malformed text, and a publication that contains multiple possible deadlines.
  • ✓Idempotency tests send the same event more than once and confirm that the consuming system does not create duplicate tasks, comments, alerts, or process records. This is particularly important when a webhook is retried after a timeout.
  • ✓Ordering and replay tests verify that a consumer handles late-arriving events. A publication may be delivered before a related document, or a correction may arrive after the original event, so the integration needs explicit rules for updates and reconciliation.
  • ✓MCP and LLM compatibility tests check that connected assistants still recognize the process identifier, publication date, source text, documents, and extraction confidence. A model connector should not infer that a renamed field is equivalent unless the mapping is explicitly provided.
  • ✓Performance and rate-limit tests measure realistic bursts. A large legal department can receive many publications at once, so test pagination, retry backoff, queue growth, response time, and behavior when a dependent ERP is temporarily unavailable.
  • ✓Postman collections or equivalent API scripts can provide a practical smoke-test layer for operations teams. Run authentication, health, sample publication, pagination, duplicate delivery, and error-response scenarios in a staging environment before production approval.
  • ✓Contract tests should run in CI/CD on pull requests, not only during release week. The Pact documentation describes a consumer-driven approach that can help teams verify provider and consumer expectations independently.

A breaking change is not only a deleted endpoint. It includes any modification that can alter a legal decision, task, deadline, or record. Changing the interpretation of data_publicacao, lowering the precision of numero_processo, or returning an empty value where consumers expect a document can be breaking even when the HTTP route remains unchanged.

Use a change notice that answers five questions: what is changing, why it is changing, who is affected, when it becomes effective, and how to migrate. Attach before-and-after payloads, field mappings, test cases, and a rollback plan instead of relying on a short release note.

Communication should reach technical and operational owners. The API team may know that confianca_extracao changed, while the legal operations team knows that scores below a threshold send publications to manual review. Both groups need to validate the impact.

For offices that centralize multiple correspondents, create an integration inventory with the consumer name, owner, contract version, data scope, last successful call, and migration status. Without this inventory, an apparently inactive integration may still support a critical client or deadline process.

A practical schedule includes an advance notice, a test environment, a migration deadline, a parallel period, reminder messages, and a final retirement confirmation. Preserve the old version for a defined period, but avoid indefinite support because two interpretations of the same field can create operational ambiguity.

The NIST Secure Software Development Framework reinforces the value of controlled changes, verification, and traceability throughout the software lifecycle. Those principles are especially relevant when an integration affects records that support legal work.

Applying API contract versioning to Pocket Jurídico integrations

Pocket Jurídico is designed for legal teams that monitor names, terms, cases, publications, and procedural movements across more than 490 journals and courts. When those publications are synchronized with an ERP, CRM, legal management platform, or internal application, the integration should treat each publication as an auditable business event rather than as an unstructured notification.

A useful implementation starts with a mapping table. For example, numero_processo can map to the ERP case key, data_publicacao can map to the publication-date field, tribunal can map to the court code, and confianca_extracao can determine whether an extracted deadline enters automatic processing or manual review.

The field confianca_extracao deserves special care. A score of 0.94 may mean that extraction is highly reliable, but it does not prove that the suggested deadline is legally correct. Keep the original text, extracted value, source metadata, and human confirmation status available to preserve context.

The same principle applies when teams connect publications to ChatGPT, Claude, Gemini, or an MCP connector. The assistant should receive stable identifiers and source content, while the contract defines which values are authoritative and which are suggestions. This prevents an AI-generated summary from replacing the publication that a lawyer may need to inspect.

A safe CI/CD pipeline for this ecosystem can combine OpenAPI schema checks, consumer-driven contract tests, anonymized court fixtures, Postman scripts, duplicate-event tests, and MCP or LLM response checks. Run the pipeline against a staging feed, then compare the old and new payloads for process identity, publication date, document count, and extracted action.

This approach supports gradual adoption without requiring a legal team to abandon existing software. Pocket Jurídico can sit alongside an established ERP or legal platform, while the contract and mapping layer prevent the same publication from becoming multiple manual tasks in disconnected systems.

A low-risk rollout plan for firms with multiple ERPs and correspondents

  1. 1

    Inventory every consumer

    List internal applications, outsourced law firms, correspondents, reporting jobs, spreadsheets generated by automation, AI connectors, and calendar workflows. Record the owner and business consequence if each integration stops receiving publications.

  2. 2

    Create a representative test corpus

    Use anonymized examples covering different courts, instances, publication formats, corrections, attachments, duplicate events, and publications with extracted deadlines. Include high-volume periods to expose queue and rate-limit problems.

  3. 3

    Freeze the contract baseline

    Publish the current schema, field dictionary, mapping table, sample payloads, authentication rules, retry policy, and error catalog. Tag this baseline in source control so every future change has a clear comparison point.

  4. 4

    Deploy compatibility adapters

    If a new naming convention is needed, translate between old and new fields at the boundary instead of forcing every consumer to change at once. Adapters should be temporary, observable, and covered by tests.

  5. 5

    Choose a pilot group

    Start with one low-risk internal consumer and one representative external consumer. Confirm that publications arrive, processes match, extracted values are preserved, and tasks are not duplicated before expanding the rollout.

  6. 6

    Run old and new paths in parallel

    For a defined period, compare event counts, delivery latency, HTTP errors, missing fields, duplicate records, and created tasks. Investigate discrepancies rather than assuming that equal message counts prove functional equivalence.

  7. 7

    Define rollback triggers

    Examples include a sudden increase in unmatched process numbers, a drop in document availability, duplicate deadline tasks, or a material increase in manual review. Make rollback executable without waiting for a developer who may be unavailable.

  8. 8

    Close the migration formally

    Collect consumer sign-offs, archive the comparison report, update the integration inventory, and communicate the retirement date. Keep support documentation available for audit and future onboarding.

Common API contract mistakes in judicial publication monitoring

The first mistake is treating optional fields as harmless. A consumer may technically accept a missing documentos array, but its workflow may interpret the absence as proof that no document exists. Define the difference between an empty list, a null value, an omitted property, and an unavailable source.

Another mistake is changing date formats without testing legal meaning. ISO 8601 timestamps are useful, but a consumer may need the official publication date in Brazil rather than the capture timestamp. Return both when necessary, with names that make the distinction unmistakable.

Many teams also test only successful responses. Add cases for 401 and 403 authentication failures, 404 records, 409 duplicates, 429 rate limits, 5xx provider errors, malformed payloads, and timeout retries. Every error should tell the consumer whether it is safe to retry.

Avoid relying on production data as the only test source. Build anonymized fixtures that preserve structural variety without exposing sensitive case information, personal data, or confidential documents. The Brazilian data protection authority, ANPD provides official regulatory material that can inform data governance decisions under Brazil's privacy framework.

Finally, do not make the API contract responsible for decisions that belong to legal review. A contract can preserve source text, provenance, confidence, and extraction status, but it cannot guarantee that an automated deadline interpretation is correct in every procedural context.

Before approving a release, ask whether the team can answer these questions: Which consumers are affected? What happens to old payloads? Can an event be replayed? How is a duplicate detected? Which field is authoritative? How will a lawyer know that a value was extracted rather than confirmed? If the answers are unclear, the contract is not ready.

Frequently Asked Questions

What is an API contract in a legal integration?▼

An API contract is a documented agreement about how two systems exchange data. It defines endpoints, authentication, fields, data types, required and optional values, errors, event behavior, and versioning rules. In a legal publication workflow, it should also explain the meaning of process numbers, publication dates, source text, documents, and extracted confidence scores.

How can I version a judicial publication API without interrupting my ERP?▼

Use an explicit versioning strategy and introduce compatibility before removing old behavior. Add new fields alongside legacy fields, test the ERP with representative payloads, run both paths in parallel, and monitor duplicates, missing data, task creation, and delivery latency. Retire the old version only after identified consumers have migrated and a rollback plan has been tested.

Is adding a new API field always a non-breaking change?▼

No. Adding an optional response field is often compatible, but some consumers fail when they deserialize unknown properties or validate an exact schema. A new field can also change operational behavior if an automation begins using it without understanding its semantics. Test the actual consumers and document whether the field is informational, authoritative, extracted, or AI-generated.

Which tests should I run before changing numero_processo or data_publicacao?▼

Run schema validation, field-mapping, consumer contract, fixture, idempotency, replay, and end-to-end workflow tests. Confirm that the process identifier remains stable, the publication date retains its intended meaning, and downstream systems create no duplicate records or incorrect deadlines. Include examples from different courts and cases with missing documents, corrections, and delayed events.

How should confidence scores from publication extraction be represented?▼

Define the scale precisely, such as a decimal from 0 to 1 or a percentage from 0 to 100, and never change that convention silently. Document whether the score measures text extraction, classification, deadline identification, or another task. Preserve the original publication and mark the extracted result as requiring human confirmation when the workflow or legal risk demands it.

How do API contracts work with MCP and legal AI assistants?▼

The contract gives the connector stable names, types, identifiers, source content, and provenance that an MCP server or AI assistant can use consistently. It should distinguish authoritative source data from summaries, suggested actions, and extracted deadlines. Test prompts and tool responses after contract changes to ensure that ChatGPT, Claude, Gemini, or another connected assistant still retrieves the correct process and publication context.

How can a law firm manage breaking changes across multiple correspondents?▼

Maintain an inventory of every consumer, owner, contract version, and business impact. Send a migration notice with before-and-after payloads, a test environment, a deadline, support contacts, and rollback instructions. Use a pilot and parallel delivery period so the firm can validate the new flow before all correspondents and outsourced offices depend on it.

Does an API contract replace human review of extracted legal deadlines?▼

No. The contract improves consistency, traceability, and safe system behavior, but it cannot determine whether every extracted deadline is legally correct. Keep the source publication, extraction result, confidence, and review status together so a lawyer can validate important actions without searching across separate systems.

Build a more reliable publication workflow

Learn more about Pocket Jurídico

Share this article

Pocket Jurídico (lawsuits in Brazil)Pocket Jurídico (lawsuits in Brazil)

Pocket Jurídico is legal software for monitoring lawsuits and court publications in Brazil, featuring automation, AI, and an integrated view of case workflows.

Pocket Jurídico (lawsuits in Brazil)

Discover Pocket Jurídico

Discover Pocket Jurídico

© 2026 Pocket Jurídico