json-schema

SOAP is nowadays about as popular as VB.NET (as in not very). But one of the few things that the orgy of XML had going for it was a strong upfront description of operations and the data they exchanged.

In a world of REST and likely JSON this can feel sorely missing. Sure, REST services should be self describing. But when you’re trying to give a specification to team of what to build, building it first doesn’t really seem like the right answer (although admittedly, probably more fun).

You’ve got a number of ways you could approach this. I typically favor just writing some documentation and a few examples similar to the REST details you’ll find from most popular web APIs. However an enterprising enterprise developer colleague of mine (who was  likely feeling XML withdrawal symptoms) Google’d his way across json-schema and suggested it.

json-schema is literally the json based equivalent of what xml-schema is to xml, a way to describe what you’re expecting in an instance using the format itself. I was initially not so keen. The examples look horribly wordy. However after working through a few real cases myself I found the grammar very simple to remember and therefore quick to write.

{
    "type": "object",
    "additionalProperties": false,
    "properties": {
        "messages": {
            "type": "array",
            "required": true,
            "items": {
                "type": "string",
                "minLength": 1
            },
            "minItems": 1
        }
    }
}

It’s pretty simple. You define properties and a description of how they should appear. properties define what keys are on an object, items define what items should be in an array. The full specification is remarkably easy to read and the bulk of it fits on less than a couple of printed pages.

The above specification would successfully validate against the following JSON object.

{
    "messages": [
        "one"
    ]
}

There are a number of tools for working with json-schema. However I couldn’t find anything online to just quickly mess around with schemas and see them pass or fail against data thrown at them. So I threw together a horribly quick and dirty test app using JSV (a browser compatible implementation of json-schema) and couple of Ace text editors.

json-schema-tester

Code is of course available on GitHub.

Just incase you were wondering how far HTML(5) could go…

This is a video demonstrating Cloud9 IDE from the ajax.org folks. It’s a few months old but I was just reminded of it by some recent tweeting. It’s incredible and really promising stuff. More importantly, it really demonstrates that a lot is possible with the technology in Chrome+Firefox today.

You can pull it down from Github and try it yourself now.


Originally posted on Thoughts from David Padbury.