Contracts before model calls

API-First AI Integration

Define an AI integration API around business operations, request identity, versions and observable outcomes, with an illustrative proposal contract and failure table.

API-first AI integration means agreeing the operation and its contract before building the model-driven implementation behind it. The interface should expose a useful business capability, such as preparing a review proposal, while preserving the application rules that decide who may request it and what counts as completion. A generic endpoint that accepts arbitrary prompts leaves too much of that contract implicit.

For application teams in Saudi organisations, this approach is especially useful when Arabic and English interpretation must join an existing permission model and record lifecycle. The language model can change behind a stable boundary, but only if the boundary specifies meaning as well as JSON shape. This is one implementation pattern within AI integration and delivery.

Define a business operation instead of a model wrapper

Choose an operation name that describes the allowed outcome. “Create pallet-condition review proposal” tells the caller more than “run AI”. Define the eligible source, target entity, required evidence, expected result and exclusions. In this illustrative warehouse example, AI prepares an observation from a permitted condition survey. It cannot adjust stock, assign liability or release a pallet for use.

Keep model-specific options behind the integration service unless callers have a real reason to control them. An application should not need to know a provider model identifier to request a review proposal. Conversely, do not hide material behavioural changes behind an unchanged endpoint: a new model or prompt still needs evaluation against the operation contract.

The OpenAPI Specification supports a machine-readable description of HTTP interfaces. Use it to document requests, responses and authentication requirements. Supplement it with business rules, examples and lifecycle semantics that schema validation cannot establish.

An illustrative request contract

The following payload is a proposed application design, not a supported API from a named warehouse product. The integration obtains identity and organisational scope from verified application context. A user-supplied organisation name inside a prompt is not proof of access.

{
  "operationId": "demo-condition-704",
  "source": {
    "surveyId": "survey-704",
    "revision": "3"
  },
  "target": {
    "palletId": "pallet-304",
    "expectedRevision": "12"
  },
  "outputLocale": "ar",
  "requestedOutcome": "review_proposal"
}

Define each identifier in the contract: who creates it, where it is unique and how long it remains meaningful. The source revision pins the evidence used for interpretation. The target revision prevents a proposal from being applied to a state that changed after the comparison. The requested outcome constrains the operation; it is not permission to execute it.

Validate required fields, allowed values and resource existence before model work where possible. Then check that the verified requester can read the source and target and request this operation. Reject inconsistent references, such as a survey belonging to a different authorised project, even when both identifiers are syntactically valid. See integration access control for the identity and resource boundary.

Separate accepted work from completed work

If analysis may exceed the caller deadline, accept a durable job and return its status location. HTTP semantics in RFC 9110 define 202 Accepted as accepted for processing, not completed processing. The API should make that distinction visible in both its response and the user interface.

Define an application state machine, for example accepted, analysing, awaiting review, submitted, confirmed, rejected and unresolved. Some states describe model work; others describe the receiving application. A confirmed proposal is different from a confirmed stock change, which this example excludes entirely.

Give status responses an operation identity, current state, update time, permitted next actions and a result reference when available. Avoid invented percentage progress if the system cannot estimate it meaningfully. Protect status and result reads so that guessing an operation identifier does not reveal another team's survey.

Make request identity survive a retry

The caller should use the same defined identity when retrying the same intended operation. The receiving service needs a durable record linking that identity to the request parameters and outcome. Decide the scope of uniqueness, the retention horizon and how a retry after that horizon is handled. A random identifier generated on every retry cannot suppress duplicate business work.

If the same identity arrives with different source revision, target or requested outcome, treat it as a conflict to resolve. Do not silently return an old result for a new intent. AWS's idempotent API guidance explains the importance of an explicit request-identity contract. The exact storage and retention design must fit the application and replay requirements.

There is also a concurrency race: two requests with the same identity may arrive together. Checking a ledger and then creating a proposal in separate unprotected steps can still create duplicates. The implementation must coordinate identity reservation and its local state change, then reconcile any external side effect through the destination's supported mechanism. Document the boundary of the guarantee instead of claiming universal exactly-once delivery.

Distinguish failure classes in the response contract

Illustrative API outcomes and caller behaviour
ConditionContract meaningCaller action
Malformed or unsupported inputNo eligible operation acceptedCorrect the request; do not retry unchanged
Permission deniedRequested access or action is not allowedUse the authorised escalation route
Target revision changedProposal assumptions are staleRetrieve current state and recompare
Temporary processing pressureService cannot currently accept or execute the work as specifiedFollow the documented retry or queue policy
Destination response lostBusiness outcome remains unknownQuery and reconcile the existing operation
Insufficient source evidenceInterpretation cannot safely completeRoute to review or request better evidence

RFC 9457 problem details provides a standard format for describing HTTP API errors. A consistent machine-readable problem type helps callers choose the correct action. Avoid exposing credentials, private document text or internal stack traces in the explanation.

Keep transport status and business state coherent. A successful status lookup can legitimately report an unresolved business operation. A schema-valid model response can still contain unsupported observations. Validate evidence and allowed action separately rather than treating every parsed response as success.

Specify cancellation and status retention

A cancellation request is itself an operation with a defined outcome. If analysis has not started, cancellation may prevent the work. If a proposal has already been accepted by the destination, cancelling the local job does not remove that record. Return the actual state and the authorised next step rather than presenting every cancellation request as an immediate reversal.

Define how long clients can query a completed or unresolved operation and how that period relates to retry and reconciliation horizons. Deleting the status record too early can make an old request look new or leave the caller unable to distinguish absence from expired history. Retain only the evidence needed under the agreed data policy, but preserve the minimum identity and outcome information needed for safe behaviour. Test a late retry and a cancellation arriving at the same time as destination confirmation; both expose lifecycle gaps that a successful normal request will miss.

Version meaning, not only field names

Adding an optional field may be compatible for some consumers, but changing a unit, date interpretation, enum meaning or default action can break them without changing the JSON shape. Record these semantic contracts. In the pallet example, “condition” must not change from an observation label to a release decision while keeping the same field name.

Establish a compatibility policy with representative consumers. Test omitted fields, unknown optional fields, new enum values and older clients according to the actual policy. Publish deprecation notices and migration evidence where needed. Avoid requiring clients to infer a behaviour change from a provider release note unrelated to your application contract.

Pin the evaluated model, prompt and validation configuration in an internal release manifest. The public operation version and internal configuration version serve different purposes. A prompt correction may preserve the contract, but it still needs a record and regression evidence. Use the integration testing strategy to connect contract tests with business cases.

Design observability and capacity into the boundary

Carry a correlation identifier through intake, model processing, review and destination submission. Keep it distinct from the identity used to prevent duplicate operations: one business operation may have several transport attempts. Record enough information to reconstruct the sequence while keeping sensitive source content out of routine logs. The audit-logging guide develops that evidence model.

Set limits on request size, concurrent work and accepted document types. Explain whether excess demand is rejected, queued or deferred. Measure completed useful operations and unresolved outcomes alongside API latency. Counting successful HTTP calls can conceal a review backlog or a growing number of unconfirmed destination writes.

If downstream applications need notification, publish an event only at the state transition promised by its contract. The event-driven integration guide covers the separate publication and consumption guarantees. Do not let an API response and an event disagree about whether a proposal was merely prepared or accepted.

Keep the API inside the complete delivery scope

An API-first design improves the boundary, but operating the workflow also requires review, exception handling, monitoring and ownership. The comparison of full integration and an API-only approach helps define what remains beyond the endpoint. For product teams, Trusted Data's SaaS integration article provides related commercial context on embedding AI within an existing application.

Discuss an API contract for an AI integration with a sample request, the authorised outcome, the target-state rules and the failure cases that must remain understandable to callers.

FAQ

Your questions, answered.

What does API-first mean for an AI integration project?

It means defining the business operation, request and response semantics, identity, permissions, failure states and compatibility expectations before building the model implementation. The API can then remain stable while internal components evolve under evaluation. A generic prompt endpoint is not automatically API-first in this sense because it may leave the business outcome and authority undefined.

Is a valid JSON response enough to accept an AI result?

No. Schema validation establishes shape and some value constraints. It does not establish factual support, correct target identity, current permission or successful application completion. Validate those properties separately. An observation can be structurally valid yet unsupported by the source, and a correctly shaped command can still request an operation the caller is not allowed to perform.

How should an AI API handle retries after a timeout?

First establish whether the outcome is known. Reuse the same operation identity for the same intended request and query the supported status or reconciliation mechanism. Define duplicate and changed-parameter behaviour in the contract. Do not generate a new identity simply because the response was lost; the receiving application may already have accepted the original operation.

What should happen when the target record changes during AI processing?

Use a version or equivalent precondition to detect the conflict before applying the proposal. Retrieve the current state and recompare or route for review according to the workflow. Preserve the original evidence and proposal history. An approval based on an older record should not silently authorise overwriting a newer change.

Does HTTP 202 mean the AI integration completed successfully?

No. It indicates acceptance for processing. Provide an authorised status resource and a clear application lifecycle that distinguishes analysis, review, submission and confirmed destination outcome. The user interface should reflect those states. A successful intake response cannot by itself establish that a receiving business application created or changed the intended record.

Which API changes can break an AI integration without changing its schema?

Changing units, default actions, enum meaning, source precedence, language interpretation or approval semantics can break consumers even when all field names and types remain unchanged. Maintain semantic examples and consumer tests alongside the schema. Record model and prompt changes internally and evaluate them against the operation contract before release.

LET’S WORK TOGETHER

Ready to build what’s next?

Tell us about your project or the platform you want to explore, and we’ll come back to confirm a suitable time.