micronaut-projects / micronaut-json-schema

Micronaut integration with JSON schema
Apache License 2.0
2 stars 1 forks source link

Support JSON Schema #2

Closed andriy-dmytruk closed 6 months ago

andriy-dmytruk commented 7 months ago

Feature description

Task description

We need to be able to generate JSON schema from beans. The JSON schema should mimic how an object would get serialized the best it can and contain additional information, like description where possible.

The JSON schema reference can be found at: https://json-schema.org/understanding-json-schema/reference. Additionally, the JSON schema specification is at https://json-schema.org/specification.

Proposed solution

Create micronaut-projects/micronaut-json-schema project.

A JSON schema may be generated by annotating a particular type:

@JsonSchema
@Serdeable // optional
record Person(
    String name, 
    int age
) {}

It will be generated with annotation processing by writing the file to the build META-INF folder similarly to openapi. Supporting @JsonSchemaImport might also be a good idea.

It should also be possible at the member level:


@MappedEntity
record Person(
    String name, 
   // json column
    @JsonSchema
    PersonDetails details
) {}

Customization

It is best if it supports jackson and validation annotations as well as parsing javadoc from types for description.

Since some customization might be needed, the annotation will support the following fields:

public @interface JsonSchema {
    String title() default "";
    int version() default 1; // the version number
    String basename() default; // the file base name of the generated schema file     
    String description() default "";
    String uri() default ""; // the URI of schema specified in the $id property
    JsonType() default JsonType.STRING;
}

enum JsonType {
   STRING, INT // etc.
}

There annotation processor should support the following annotation processor arguments:

micronaut.json-schema.output-location=META-INF/json-schema
micronaut.json-schema.base-uri=META-INF/json-schema

NOTE: To achieve this over getSupportedOptions() in the type element visitor

We could provide a way to serve the generated schemas, as this seems like a common requirement.

While JSON schema is similar to OpenAPI in certain ways, it seems to serve a different purpose: it is primarily used for validating JSON as opposed to describing APIs. They are not compatible with each other in different ways. The references are also handled differently, see: https://json-schema.org/understanding-json-schema/structuring#light-scheme-icon

It does not seem simple to reuse OpenAPI processing logic for this, but it might be possible that some common logic could be extracted somewhere at a later time.

cc @graemerocher

sdelamo commented 7 months ago

it would be interesting to test this module generating a real json schema such as: https://github.com/getmanfred/mac