To make this discussion more concrete, imagine that you have an API that accepts a JSON blob over HTTP/POST.
The blob is expected to be something like:
{
"name": "bob",
"age": 42
}
Your code needs to handle the case where the fields aren't there, or they have invalid values (eg the wrong type, or a negative age).
You at least need to ignore this input, but if you want this to be a nice API to work with, you probably also want to return error messages that explain what the client did wrong.
You can hand-code this logic (please excuse the pseudo-code):
if (!input.hasKey("name"))
print "The 'name' key is required."
if (typeof input["name"] != "string")
print("The 'name' key is the wrong type. Expected 'string' " +
"but got %s" % typeof input["name"])
if (!input.hasKey("age"))
...
... but I think it's clear that this quickly gets tedious and error-prone. JSON schema is one possible solution:
// schema
{
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1 },
"age": { "type": "integer", "minimum": 0 }
}
}
// handler
validator = new JSONSchemaValidator(schema)
if (validator.validate(instance))
// handle the request
else
print validator.errors.join("\n")