Dead simple request validation

When you're building an API you'll write a lot of validation rules. Most of these rules are pretty dumb, checking property types and the like. Instead of writing a lot of code for these steps, you're probably using something like JSON Schema to keep your validation rules organised.

What follows is so stupidly simple I feel silly writing about it, but I haven't seen it before, so here it goes. Let's create a middleware that takes a JSON Schema to validate the entire request object.

//Using a restify server.
server.get('/foo', [
    validationMW(fooSchema),
    handler
]);

A simple schema that just checks a single header looks like this.

{
    "title": "root",
    "type": "object",
    "required": [ "headers" ],
    "properties": {
        "headers": {
            "type": "object",
            "required": [ "my-header" ],
            "properties": {
                "my-header": {
                    "type": "string",
                    "enum": ["foo", "bar"]
                }
            }
        }
    }
}

That's a lot of schema for a single property check, but as you're adding more and more rules this approach starts paying for itself quickly.

If validation fails, the server responds with a 400, but this is behaviour you can completely customize. The library can be found on NPM and has the beautiful name json-schema-validation-middleware.