Wednesday, April 22, 2015

Generating XML Schemas Painlessly and Documenting RESTful Web Services

I have been creating quite a few RESTful web services that respond with both XML and JSON via Spring MVC. Normally with REST, you document the services by example, but in this case someone also wanted an XML schema.

Here was my process to generate XML schemas.
  1. Created Java classes annotated with XStream annotations
  2. Created example objects from the classes and marshalled them to XML via Spring's XStreamMarshaller
  3. Cut and pasted the XML into Freeformatter's XSD/XML Schema Generator
  4. Saved the generated .xsd file locally and tweaked it to so as to provide missing information such as:
    • Enumerations
    • set appropriate minOccurs and maxOccurs attributes on elements
  5. Validated my XML and my edited schema file by pasting them into Freeformatter's XML Validator - XSD (XML Schema)
  6. Tweaked the Java classes as necessary
  7. Rinse and Repeat until done
The process to generate JSON examples:
  1. The Java classes were annotated with Fasterxml's Jackson annotations
  2. Created example objects from the classes and serialized them using Jackson's ObjectMapper 
To generate the documentation, I leveraged the code that generated the XML and JSON examples and wrote them to individual files on the filesystem. I then created AsciiDoctor .adoc templates that described the services and included the XSD, XML, and JSON files. Running Asciidoctor against the .adoc templates generates nice HTML that includes everything.