Inferensys

Prompt

Request/Response Schema Validation Prompt

A practical prompt playbook for using the Request/Response Schema Validation Prompt in production API documentation QA workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for schema validation of documented API contracts.

Use this prompt when you need to verify that a documented API request or response schema matches the actual behavior of a live endpoint. The primary job-to-be-done is field-by-field accuracy auditing: confirming that every property name, data type, required/optional flag, constraint, and example payload in your documentation reflects what the API truly returns. The ideal user is a doc platform engineer, API technical writer, or developer-tools engineer responsible for maintaining documentation that developers trust. You should have access to a live API endpoint, a valid authentication method, and the documented schema you intend to validate—typically sourced from an OpenAPI specification, a markdown reference page, or a static JSON Schema file.

This prompt is designed for structured, deterministic comparison work. It expects you to provide the documented schema and a representative sample of actual API responses (or a tool that can fetch them). The model will produce a discrepancy report, not a rewritten schema. It will flag type mismatches (e.g., string documented but integer observed), missing fields present in the response but absent from the docs, undocumented fields, incorrect required/optional designations, and example payloads that don't conform to the stated schema. The prompt works best when you supply the schema in a standard format like JSON Schema or OpenAPI Schema Object, and the response payload as a raw JSON object.

Do not use this prompt when you need to author a schema from scratch, design a new API contract, or perform semantic review of field descriptions. It is not a substitute for contract testing in CI/CD, nor does it replace runtime schema validation middleware. Avoid using it for endpoints with highly variable or non-deterministic responses (e.g., those containing timestamps, random IDs, or AI-generated text) unless you first normalize those fields. For high-risk APIs—such as those handling payments, health data, or authentication—always pair the model's output with automated JSON Schema validation and a human review step before publishing documentation changes.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Schema validation prompts are precise but brittle—they excel at structured comparison but fail when ground truth is ambiguous or the schema itself is the source of error.

01

Good Fit: Spec-to-Implementation Audits

Use when: you have a machine-readable source of truth (OpenAPI spec, JSON Schema, protobuf definitions) and a set of documented schemas to validate against it. The prompt excels at field-by-field comparison, type checking, and constraint verification. Guardrail: always provide both the spec and the documented schema as structured inputs, not free-text descriptions.

02

Bad Fit: Ambiguous or Undocumented APIs

Avoid when: the API lacks a formal specification or the spec itself is incomplete. The prompt cannot invent ground truth—it will hallucinate expected types or miss missing fields entirely. Guardrail: if no spec exists, use a behavior-driven approach that calls the live API and captures actual responses instead of relying on schema comparison.

03

Required Inputs: Schema Pair and Diff Rules

What you need: a source schema (OpenAPI, JSON Schema, or equivalent), a target schema extracted from documentation, and explicit comparison rules (strict vs. lenient type matching, whether to flag undocumented fields, how to handle deprecated parameters). Guardrail: include a [CONSTRAINTS] block that defines acceptable variance—without it, the prompt will flag every optional field as a potential issue.

04

Operational Risk: False Positives from Version Drift

What to watch: the prompt will flag every mismatch between spec and docs, but some mismatches are intentional—deprecated fields still in the spec, unreleased features documented early, or version-specific behavior. Guardrail: require a [VERSION_CONTEXT] input that specifies which spec version and doc version are being compared, and whether pre-release or deprecated fields should be excluded from the diff.

05

Operational Risk: Schema Complexity Overload

What to watch: large specs with nested objects, oneOf/anyOf unions, and recursive references can produce comparison reports so verbose they become unusable. Guardrail: scope the prompt to a single endpoint or resource per run. Use a [SCOPE] placeholder to limit comparison depth and exclude internal-only fields that aren't part of the public documentation contract.

06

When to Escalate: Human Review for Semantic Mismatches

What to watch: the prompt catches syntactic errors (wrong type, missing field) but cannot judge whether a description is misleading, incomplete, or technically correct but confusing. Guardrail: route any field where the description changed but the type stayed the same to a human reviewer. Flag description-only diffs separately from type or constraint violations.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for comparing documented API schemas against actual runtime behavior, producing a structured field-by-field validation report.

This prompt template is the core instruction set for a schema validation workflow. It is designed to be dropped into an AI harness that supplies the documented schema, a live response payload, and the expected output format. The prompt instructs the model to act as a meticulous API auditor, comparing every field, type, constraint, and example value without making assumptions or skipping optional parameters. Use this template when you have a source of truth for the expected schema—such as an OpenAPI specification, a JSON Schema file, or a manually curated documentation extract—and a sample of the actual API's response body.

markdown
You are an API documentation auditor. Your task is to compare a documented API schema against a live response payload and produce a strict, field-by-field validation report.

## INPUTS
- **Documented Schema:** [DOCUMENTED_SCHEMA]
- **Live Response Payload:** [LIVE_RESPONSE_PAYLOAD]
- **Schema Format:** [SCHEMA_FORMAT] (e.g., OpenAPI 3.0, JSON Schema Draft 7)
- **Endpoint Context:** [ENDPOINT_CONTEXT] (e.g., GET /users/{id})

## CONSTRAINTS
- Compare every field in the documented schema against the live payload.
- Flag fields present in the live payload but missing from the documented schema.
- For each field, check: type, format, required/optional status, nullable status, constraints (min/max, pattern, enum), and example values.
- Do not hallucinate fields. Only report on what is present in the inputs.
- If the documented schema is ambiguous, flag it as a documentation gap rather than assuming intent.
- Classify each finding by severity: `error` (breaking contract), `warning` (likely unintentional), or `info` (addition or clarification).

## OUTPUT SCHEMA
Return a single JSON object conforming to this structure:
{
  "endpoint": "string",
  "schema_source": "string",
  "validation_summary": {
    "total_fields_documented": "integer",
    "total_fields_in_payload": "integer",
    "errors_count": "integer",
    "warnings_count": "integer",
    "info_count": "integer"
  },
  "findings": [
    {
      "field_path": "string (e.g., data.attributes.name)",
      "documented_type": "string | null",
      "actual_type": "string",
      "documented_constraints": "object | null",
      "actual_value_sample": "string",
      "severity": "error | warning | info",
      "category": "type_mismatch | missing_from_docs | missing_from_payload | constraint_violation | example_invalid | undocumented_field",
      "description": "string explaining the discrepancy",
      "suggested_fix": "string"
    }
  ]
}

## EXAMPLES
[EXAMPLES]

## RISK LEVEL
[RISK_LEVEL]

If [RISK_LEVEL] is `high`, flag any undocumented breaking change as a blocking error and recommend human review before publication.

To adapt this template, replace the square-bracket placeholders with your specific inputs. [DOCUMENTED_SCHEMA] should contain the full schema object, not just a reference. [LIVE_RESPONSE_PAYLOAD] must be a real, unmodified response body captured from the running API. [EXAMPLES] is optional but strongly recommended: provide one or two few-shot examples of correct findings to calibrate the model's severity classification and description style. [RISK_LEVEL] should be set to high for externally-facing, stable, or revenue-critical APIs where a breaking change in documentation could cause customer incidents. For internal or beta APIs, medium or low is acceptable. After copying the template, wire it into a harness that validates the output JSON against the schema defined in the prompt itself—this prevents the model from drifting the report structure over repeated runs.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Request/Response Schema Validation Prompt. Each placeholder must be populated before the prompt is assembled. Validation notes describe how to verify the input is correct before execution.

PlaceholderPurposeExampleValidation Notes

[SOURCE_SPEC]

The authoritative API specification to validate against

openapi: "./specs/petstore-v3.yaml"

Must parse as valid OpenAPI 3.x or JSON Schema. Fail if spec is unparseable or references unresolvable $ref nodes.

[DOCUMENTED_SCHEMA]

The schema as described in the documentation under review

{"type": "object", "properties": {"id": {"type": "integer"}}}

Must be valid JSON or YAML. Validate structural integrity before passing to prompt. Reject if not a valid schema object.

[SAMPLE_PAYLOADS]

Real request/response payloads captured from the live API

[{"request": {...}, "response": {...}}]

Minimum 3 payloads required. Each must include both request and response. Validate HTTP status codes are present. Null allowed if endpoint has no request body.

[ENDPOINT_METADATA]

Method, path, and context for the endpoint being validated

{"method": "POST", "path": "/v2/pets", "auth_required": true}

Method must be a valid HTTP verb. Path must start with /. Auth flag must be true or false. Reject if method or path is missing.

[FIELD_WHITELIST]

Fields explicitly excluded from validation

["x-internal-debug", "deprecated_field"]

Must be a JSON array of strings. Null allowed if no exclusions. Each entry must match an actual field name in either spec or docs.

[STRICTNESS_LEVEL]

Controls whether warnings or only errors are reported

"strict"

Must be one of: "strict", "lenient", "spec_only". Strict flags all mismatches. Lenient ignores optional field differences. Spec_only only checks spec-defined constraints.

[OUTPUT_FORMAT]

Desired structure for the comparison report

"field_by_field"

Must be one of: "field_by_field", "summary", "diff_only". Field_by_field produces per-field comparison. Summary produces aggregate counts. Diff_only reports only mismatches.

PROMPT PLAYBOOK

Implementation Harness Notes

How to integrate the schema validation prompt into a CI/CD pipeline with automated diffing, retries, and human review gates.

This prompt is designed to be the reasoning core of an automated documentation testing harness, not a standalone chat interaction. The primary integration pattern is a CI/CD job that triggers on changes to either the API specification (e.g., an OpenAPI file) or the human-authored documentation. The harness fetches the live API's response for a given endpoint, feeds both the documented schema and the live response body into the prompt, and parses the structured comparison report. The model's output should be treated as a sophisticated diff engine that understands semantic equivalence, not just structural identity.

To wire this up, build a script that: (1) parses the target endpoint and its documented schema from your source of truth; (2) makes a live API call with appropriate authentication and a representative payload; (3) constructs the prompt by injecting the documented schema into [DOCUMENTED_SCHEMA] and the live JSON response into [LIVE_RESPONSE]; and (4) calls the LLM with response_format set to a strict JSON Schema that matches the expected SchemaComparisonReport output. Implement a retry wrapper with a maximum of two attempts. If the first response fails JSON Schema validation, feed the raw output and the validation error back into the model with a repair instruction before retrying. If the second attempt also fails, escalate the check to a NEEDS_HUMAN_REVIEW status and log the raw output for a developer to triage.

The harness must include a severity classifier that gates CI pass/fail. Parse the model's findings array and block the pipeline if any finding has a severity of error. Findings with a severity of warning should post a non-blocking comment on the pull request. To reduce false positives, maintain a small suppression file (e.g., schema-suppressions.yaml) that allows teams to mute known acceptable discrepancies, such as intentionally undocumented internal fields or write-only parameters that don't appear in read responses. Every suppression entry must include a reason and an expiration date to prevent drift. Finally, log every prompt invocation, the raw model response, and the final pass/fail verdict to your observability platform to track accuracy trends and identify endpoints that frequently generate false positives.

IMPLEMENTATION TABLE

Expected Output Contract

Define the exact fields, types, and validation rules the prompt must return. Wire these into your application's schema validator before accepting the output.

Field or ElementType or FormatRequiredValidation Rule

schema_diff_report

JSON Object

Top-level object must contain a 'comparisons' array and a 'summary' object. Parse check: valid JSON.

comparisons

Array of Objects

Must be a non-empty array. Each element must have 'field_path', 'doc_value', 'actual_value', and 'match_status' keys.

comparisons[].field_path

String (JSONPath)

Must be a valid JSONPath expression pointing to the field in the documented schema. Regex: ^$.(\w+|[\d+])(.\w+|[\d+])*$

comparisons[].doc_value

String or null

The value or type description from the documentation. Null allowed only if the field is undocumented.

comparisons[].actual_value

String or null

The value or type observed from the live API or spec. Null allowed only if the field is missing from the actual response.

comparisons[].match_status

Enum: match | mismatch | missing_in_doc | missing_in_api

Must be one of the four enum values. 'match' requires doc_value and actual_value to be equivalent by type and constraint.

summary

JSON Object

Must contain integer fields: 'total_fields_compared', 'matches', 'mismatches', 'missing_in_doc', 'missing_in_api'. Sum of status counts must equal total_fields_compared.

summary.severity

Enum: pass | warning | fail

Fail if any mismatch or missing_in_api exists. Warning if only missing_in_doc exists. Pass if all match_status are 'match'.

PRACTICAL GUARDRAILS

Common Failure Modes

Schema validation prompts fail in predictable ways when comparing documented schemas against live API behavior. These cards cover the most common failure modes and the guardrails that prevent them before they reach production.

01

Hallucinated Field Mismatches

What to watch: The model reports type mismatches or missing fields that don't actually exist, especially when comparing large schemas or when the documented schema uses different naming conventions than the live response. The model confuses semantically similar fields and flags false positives. Guardrail: Always pair the prompt with a deterministic JSON Schema validator that performs the actual structural comparison. Use the model only to interpret discrepancies the validator finds, not to perform the comparison itself.

02

Nested Object Drift

What to watch: The model correctly validates top-level fields but misses type mismatches, missing constraints, or extra fields nested two or more levels deep. Deeply nested optional objects are especially prone to silent failures. Guardrail: Require the prompt to produce a recursive field-by-field report that explicitly walks every nesting level. Validate the output by spot-checking at least one deeply nested path per schema against the raw API response.

03

Enum Value Blindness

What to watch: The model confirms that a field is a string but fails to check whether the actual response values match the documented enum. This is common when the live API returns new or undocumented enum members. Guardrail: Add an explicit instruction to extract all observed enum values from sample responses and diff them against the documented enum list. Flag any value present in responses but absent from documentation as a critical finding.

04

Example Payload Contamination

What to watch: The model treats the documented example payload as ground truth and flags the live API response as incorrect when they differ, even when the live response is valid and the example is stale. Guardrail: Instruct the model to treat the OpenAPI schema or spec as the source of truth, not the example payload. Add a separate validation step that compares the example payload against the schema to detect stale examples before schema validation runs.

05

Optional vs Required Confusion

What to watch: The model flags a field as missing when it is correctly absent because the field is optional and the test response didn't include it. Conversely, it may fail to flag a truly required field that is missing. Guardrail: Require the prompt to explicitly reference the required array from the schema for every field it evaluates. Test with multiple sample responses that exercise both present and absent optional fields to confirm the guardrail holds.

06

Format Constraint Neglect

What to watch: The model validates that a field is a string but ignores format constraints like date-time, uri, email, or pattern. A field that returns a malformed ISO timestamp passes type checking but fails format validation silently. Guardrail: Add a dedicated format validation pass that checks every field with a format or pattern constraint against the actual response value. Use a deterministic regex or format parser for this check rather than relying on model judgment.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of a schema validation report before integrating it into a CI/CD pipeline or doc review workflow. Use these standards to gate whether the prompt output is actionable.

CriterionPass StandardFailure SignalTest Method

Field Coverage Completeness

Report identifies every field present in the live API response, including optional and nullable fields, with zero omissions.

Report misses fields that exist in the live response payload, especially nested or conditionally returned fields.

Diff the set of documented fields against a JSON Path extraction of all keys from a representative live response sample.

Type Accuracy

Every field's documented type matches the actual JSON type observed in the live response (e.g., string, number, boolean, array, object).

A documented type of integer is reported as matching a live number, or a documented string is reported as matching a live null without flagging the nullability gap.

Validate each field's typeof against the documented schema. Flag any mismatch, including integer vs. float distinctions if the spec requires it.

Constraint Validation

All documented constraints (minLength, maxLength, pattern, enum, minimum, maximum) are verified against live values and flagged if violated.

A documented enum of ['active','inactive'] passes validation when the live API returns 'pending' without the report flagging the missing enum value.

For each constraint in the OpenAPI or JSON Schema, assert the live value satisfies the rule. Log a violation for any failure.

Example Payload Fidelity

The report flags any documented example payload that does not strictly validate against the documented schema or does not match the shape of live responses.

A documented example includes a field not in the schema, or uses a string where an integer is required, and the report marks it as valid.

Validate the documented example payload against the documented JSON Schema using a standard schema validator. Flag any validation errors.

Deprecation and Sunset Header Detection

The report flags any field or endpoint present in the live API that is marked as deprecated in the spec but still functional, noting the sunset date.

A deprecated field with a past sunset date is still active in the live API, but the report does not flag it as a high-severity drift issue.

Cross-reference the OpenAPI deprecated flag and sunset headers against the actual HTTP response headers from the live endpoint.

Error Response Schema Match

The report validates that documented error response schemas match the actual error bodies returned by the API for common failure modes (400, 401, 404, 500).

The documented error schema specifies a 'detail' field, but the live API returns 'message', and the report does not flag this structural mismatch.

Trigger a known 400 error via an invalid request. Validate the live error response body against the documented error schema for the endpoint.

Nullable vs. Required Disambiguation

The report correctly distinguishes between a field that is missing from the response, a field that is present with a null value, and a field that is required.

A field documented as required is missing from a 200 OK response, but the report only flags it as a type mismatch instead of a missing required field violation.

Check the live response for the presence of the key, not just its value. A missing key is a violation of 'required'; a null value is a violation of a non-nullable type.

Report Actionability

Every flagged mismatch includes the exact JSON path, the documented value, the observed value, and a severity classification (Critical, Warning, Info).

A mismatch is reported as 'Type error in response' without specifying the field path, expected type, or actual type, making it impossible to fix.

Parse the report output. Assert that every finding object contains non-null values for path, expected, actual, and severity fields.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt without external validation tooling. Rely on the model's own schema output and a manual spot-check of 5-10 fields. Accept a simple pass/fail summary instead of a detailed diff report.

Prompt modification

Remove the [VALIDATION_SCHEMA] placeholder and replace it with inline instructions: "Compare the documented fields against the sample response and list any mismatches you find." Drop the structured output requirement and ask for a bulleted list.

Watch for

  • The model hallucinating field names that don't exist in either source
  • Missing type mismatch detection when both values are strings
  • No quantitative completeness metric, making it hard to track improvement over time
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.