I am attempting to generate a data model matching a JSON schema.
the schema is draft v7 and i cannot find any IDE (IntelliJ, Eclipse) or online resource that can consume it and allow me to generate example json messages.
I either see no error messages at all or a generic one saying an error occurred when i attempt to load the schema.
surely there must be a standard approach to consuming a v7 json schema and generating json messages from it.
what am i doing wrong
Could you please let me know how to Generate JSON data from Json Schema V3 in Java. Is there any Java library for this?
This is what is officially known. If you find others, please submit a pull request.
https://json-schema.org/implementations.html#generators-from-schemas
I created the JSON Schema path on my localhost. Copied the Swagger-UI module. Added the url in the Swagger-UI. I am getting this error that model not found. This is very strange because the JSON has all the models associated to the JSON Schema.
Why does it try to look for something like:
http://localhost:8080/OpenClaimRequest rather looking into the definitions in JSON itself?
JS Console Error Log
I was using Swagger-UI 3.x version where as my API spec version was 1.2
API Spec 1.2 is compatible with Swagger-UI 2.x not any version higher than that.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I have some RESTful APIs on Jersey 2.17 with Jackson.
They are all on JSON style, and work very well.
But I want to generate a good RESTful Docs withJSON sample for developers.
So I tried some maven plugins,
Firstly I tried ServiceDocGen Maven Plugin,
it directly generate HTML docs with Json sample.
But it doesn’t know Jackson annotation like #JsonProperty, #JsonIgnore,
So the JSON sample is inaccurate.
Then I tried swagger-jaxrs-maven, it knows some Jackson annotation like #JsonProperty, but still can't handle #JsonIgnore. Also it is the description of the data schema, not the sample. It will fail if the API directly return a JSON string.
I also tried jaxrs-raml-maven-plugin, it can only use JAXB to generate sample which is inaccurate.
Basically My requirement is simple:
Generate endpoint URL and parameter description from JAX-RS annotation, every plugins I tried did it very well.
Generate sample JSON on payload, I don't care JSON sample data logic is correct or not, I care if the data structure is accurate. So setting fixed data on certain type is OK, like ServiceDocGen always set "text" on a string.
I believe it is not so tough to generate JSON sample: Firstly go through Java Object tree, fill in random type safe data. Then call Jackson deserializer to generate json data.
But until now I can't find any maven plugin is doing this job well.
Any suggestion ?
You can try spring-restdocs:
https://github.com/spring-projects/spring-restdocs
http://docs.spring.io/spring-restdocs/docs/current/reference/html5/
It generates documentation snippets based on tests of your endpoints (via RestAssured or MockMvc). This way you have a programmatic link between your code and your documentation.
I dont think you will find a tool out there that does exactly that.
Your best bet is to write a swagger.json file and import the swagger-ui webjar dependency.
<dependency>
<groupId>org.webjars</groupId>
<artifactId>swagger-ui</artifactId>
<version>${swagger-ui.version}</version>
</dependency>
You can then customize/override the index page of swagger-ui and hard code it to point to the localhost path to your swagger.json file or wherever you want.
If time is not a constraint, you could then write a maven plugin to scan and reverse engineer your JAX-RS annotations using reflection to generate a swagger json file. Personally, I prefer to maintain only a single json file and generate my API and models from that file.
I'd echo cosbor11's direction, Swagger is the way to go if you want to keep code and readable docs in sync. Check out Swagger Inflector which supports a service-first approach as described by Phil Hauer: https://blog.philipphauer.de/enriching-restful-services-swagger/
With Inflector, you can either start with API spec to generate stubs and proxies, or you can start service-first where your code annotations (see below) generates the Swagger spec for you:
#Api(value = "customers", description = "RESTful API to interact with customer resources.")
#Path("customers")
public class CustomerResource {
#ApiOperation(value = "Get all customers", notes = "Get all customers matching the given search string.", responseContainer = "List", response = Customer.class)
#GET
#Path("/")
#Produces(MediaType.APPLICATION_JSON)
public List<Customer> getCustomers(
#ApiParam(value = "The search string is used to find customer by their name. Not case sensetive.", required = false, defaultValue = "") #QueryParam("search") String searchString,
#ApiParam(value = "Limits the size of the result set", required = false, defaultValue = "50") #QueryParam("limit") int limit) {
List<Customer> customers = dao.getCustomers(searchString, limit);
return customers;
}
}
Once you live in Swagger/OpenAPISpec land, there are a ton of tools (beyond swagger-ui) that help you generate static docs, interactive samples, and use whatever level of metadata/defaults that are in your Swagger spec to produce usable, human-readable examples.
https://github.com/sourcey/spectacle
https://lucybot.com/
https://swaggerhub.com/
If you have problems implementing Inflector, definitely reach out to #olensmar on Twitter who works directly with #fehguy on the Swagger spec and tooling.
I finally finished my task by creating my own Java object creator.
To help other people who has the same issue, I added this project into GitHub:
ObjectTreeCreator
After this project, the remaining tasks are simple:
find all API methods by Java reflection
find return class type on every API method by Java reflection
call ObjectTreeCreator to generate an object from the class type
call Jackson ObjectMapper.writeValueAsString to generate Json string from this object
Now my RESTful doc generator works very well. it only needs about 10 seconds to generate html document for about 300 RESTful APIs.
I also added into my maven build process. So every time my build server automatically find all APIs and generate RESTful doc for me.
The generated JSON structure is exact the same as real API response.
By the way I also used Integration testing result if it exists.
ObjectTreeCreator is only used when Integration testing doesn't exist.
An automated system is going to feed the application[Play with Scala] with JSON's and the contract of the integration is that there would be no validation required on JSON's since it will be always deemed right. But for testing purposes when we seed the data more often than not we are not able to send the correct JSONs. We would like to validate the JSON's we receive based on a set of grammars. Is there a library that already does this. Or is there a better way to do this?
Example: Grammar for valid Json :
"header"->[String, mandatory],
"footer"->[String],
"someArray"->Array[String, mandatory],
"someArrayObject"->Array[
{
{"key1"->Int, mandatory},
{"key2"->String}
},
mandatory
]
and passing,
{
"header":"headerContent",
"footer":"footerContent",
"someArray":["str1", "str2"],
"someArrayObject"->[
{"key1":4, "key2":"someStringValue"},
{"key1":5, "key2":"someOtherStringValue"}
]
} // would pass
{
"header":"headerContent",
"footer":"footerContent",
"someArray":["str1", "str2"]
} // would notpass since someArrayObject though declared mandatory is not provided in the sample json
I think play-json will satisfy you play-json
In play-json you don't create a validator as it is, but a json transformer which is a validator in itself. The author of the framework wrote a series of blog-posts to show how to work with it: json-transformers
* Haven't noticed you use play) Play has play-json included by default.
You don't have to roll out your own DSLs. This is why we have schemas. Just like using XML schemas to validate your XML docs, you can define a JSON schema to validate your JSON objects. I had a similar requirement when building a RESTful web service using Play. I solved it by using the JSON Schema Validator library.
I have used the JSON Schema draft v3. The library supports draft v3 and draft v4. You can validate your schemas against possible JSON inputs using a web application that uses the same library. The web app is hosted here.
Also there are pretty nice examples that use the draft v4. You can check them out from here.
In Play 2, I have composed an action that takes the schema resource file name as input. This keeps away a lot of JSON validation code from the controller action itself.
#JsonValidate("user-register.json")
public static Result create() {
...
}
This way, all JSON Validation code stays in one place. Pretty neat :)