I'm documenting an internal REST API written ini Scala, unfortunately we are not able to integrate Swagger, so for now we are going with an in-house solution for the doc generator. I would like to generate a JSON-Schema to show how the response is when getting our resources. I'm just wondering if there is any shortcut to do this by taking advantage of the case classes already modeled.
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.
In a JSON schema, a $ref keyword is a JSON Pointer to a schema, or a type or property in a schema. A JSON pointer takes the form of A # B in which: A is the relative path from the current schema to a target schema. If A is empty, the reference is to a type or property in the same schema, an in-schema reference.
You can use the JSON parser to convert data from a string written in JSON format into a JSON object that represents the string. The JSON parser generates a schema, with keys included in the list of fields that are available for mapping into later nodes in the flow.
JSON Schema is an IETF standard providing a format for what JSON data is required for a given application and how to interact with it. Applying such standards for a JSON document lets you enforce consistency and data validity across similar JSON data.
The autoschema project is able to export JSON schema from Scala case classes. You can use it as follows:
case class MyType(myValue: Int)
AutoSchema.createSchema[MyType]
The Maven artifact seems to be no longer available but it is an SBT project available on Github so you can either copy the sources, build a Jar or add it as a dependency with SBT by putting in your build.sbt
the following:
lazy val autoschemaProject =
ProjectRef(uri("https://github.com/coursera/autoschema.git"), "autoschema")
lazy val root = (project in file(".")).dependsOn(autoschemaProject)
I tested this with SBT 0.13.7. Notice that autoschema has its own dependencies (mainly play-json 2.3.2
) so you might need to change their versions to avoid version conflicts with you own project dependencies.
As @mziccard stated, autoschema is the way to go. However, it's been a while since there has been some activity on the main repository. I took some time to fork it and update its dependencies and deprecated code (work that was done in other forks, I simply combined it). It is now published in maven central under my fork:
https://github.com/sauldhernandez/autoschema
You can use it by putting this in build.sbt
:
libraryDependencies += "com.sauldhernandez" %% "autoschema" % "1.0.0"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With