Sharing External Integration Input Specifications via JSON Schema | Ajv

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About this article
This article was created using an automated generation workflow powered by generative AI. Implementations from existing materials were cross-referenced with official documentation, organizing operation examples, constraints, and reference test results.

Verification Status: Partially cross-referenced with official documentation and implementation, and reference-tested. Browser operation for the fixed demo version has not been verified.

If required fields are missing from the JSON received from another team, the ingestion process halts. It distinguishes between missing required fields and type mismatches in its responses.

Open live demo

Key terms to know first

  • JSON Schemais a specification that expresses the structure and constraints of JSON.

  • Required fieldis a property that cannot be omitted from the input.

Thinking with requirement diagrams

Represents integration conditions as a single requirement. It ensures that the input data contains an id and that it is an integer.

requirementDiagram
    requirement ExternalRecord {
        id: R1
        text: id is present and integer
        risk: medium
        verifymethod: test
    }
    element InputValidator {
        type: Ajv
    }
    InputValidator - satisfies -> ExternalRecord

Live demo operations

Execute with an empty object. Test the id with both string and integer values.

How to interpret the results

Observe the difference between missing field errors and type errors.

Sharing the schema allows integration partners to validate against the same conditions. Even if the id is present, if it remains a string, it will be halted by the type condition.

Key code highlights

Compile the schema and use the validation function and errors.

The implementation can be found under "Implementation Code" on the demo screen.

When using it in production

Notifying the location of the error makes it easier for the integrating party to fix it.

Check sequentially for what is missing

The initial value is an empty JSON object {}. Clicking the run button is expected to display an array of validation errors. Missing the id and having the wrong id type are distinct failures. Next, entering {"id":"2"} reveals that the required item exists, but is not an integer type. Finally, entering {"id":2} satisfies the conditions of this demo. Observe not only the presence or absence of errors, but also items indicating the reason and location, such as keyword, instancePath, and params. In the case of required, the name of the missing item is included in params, so an empty instancePath does not mean there is no information.

InputExpected Result
{}Missing required field
{"id":"2"}Incorrect type
{"id":2}Pass
{"id":-1}Pass
{"id":2.5}Incorrect type
{"id":2,"extra":true}Pass
[]Not an object

The current condition allows negative numbers and extra fields to pass. If you actually want to allow only positive IDs, you set minimum. If you want to accept only specified fields, consider the condition for additionalProperties. Passing this demo does not mean the data can be registered in an actual production system.

What Each Part of the Schema Determines

Implementation uses type:object, required:[id], and a schema where properties.id specifies type:integer. type:object requires the entire data to be an object. required determines the presence of fields, and properties examines the content of fields that are present. Simply specifying a type in properties does not make that field mandatory. For example, an optional comment field can be designed to verify whether it is a string only when it is present. The key is to define the conditions for mandatory fields and the conditions for fields when they are present separately.

Ajv uses compile to create a validation function from a schema. You pass the JSON.parsed input to the validation function, which returns a success message if true or errors if false. allErrors:true is a setting to inspect multiple errors that can be obtained. In a production API, you also limit the input size and processing volume to prevent unnecessary validation load on huge inputs. If you use the same contract repeatedly, consider a design that reuses the generated validation function rather than compiling the schema every time.

The Boundary Between JSON Syntax and Business Rules

Trailing commas or missing quotation marks at the end of the input will cause JSON.parse to fail. It has not yet reached the stage where a schema can be applied. Conversely, even if the JSON syntax is correct, validation will stop if the expected fields or types differ. Separating the two allows you to communicate the cause specifically to the integrating party. Even if validation passes, whether the ID is actually registered and whether the user is authorized to access that data are separate conditions.

When sharing a contract with an external team, manage the schema version, sample inputs, and failure responses in the same location. Adding a new mandatory field may cause inputs from older clients that were previously valid to fail. Before making changes, use test data from the older version to check which cases will break. Whether to allow or reject unknown fields should also be decided from both compatibility and security perspectives.

Troubleshooting and Secure Usage

Initially, check the difference in judgment using examples of an empty object and a valid integer. If the same network error occurs in both cases, there may be a problem with loading the library rather than the input. Check the Console and Network tabs. Since error arrays change in subsequent validations, in production you extract necessary information on the spot and convert it into messages understandable to users. Do not return internal structures or confidential values carelessly.

The public demo uses fictional JSON. Browser-based judgment is merely an aid for operations, and server-side input validation and authorization must not be omitted. This reference test executed the same JSON Schema with a different validator and does not verify Ajv's specific error wording or internal structure.

Validation Scope

Reference test of the same schema using Python jsonschema 4.26.0 Draft7Validator. {}=required, id string/decimal=type, integer 2/-1 and additional properties=pass, array=type. Execution of Ajv itself and browser verification are unconfirmed.

The targets are current browsers and the course-specified Ajv 8.17.1. Communication to fetch external CDNs and Mermaid is required, and actual rendering in course materials, actual diagram drawing, and re-verification of the pinned version license remain. Since official documentation also contains descriptions of other versions, this is distinguished from proof of pinned version execution.

References

GitHub Sample

Implementation and Experimental Procedures

Document information

Article title
Sharing External Integration Input Specifications via JSON Schema | Ajv
Published
Updated
Source
https://papanda925.com/?p=18981&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL