rest-spec
Request data validating library for RESTful APIs. rest-pec can validate POST/PUT/PATCH JSON data as well as GET/DELETE query string parameters using JSON schema and is easy to use with express.js. It generates endpoint documentation on the fly too.
Example
Say, we run an API for a blog. We could define our schema for a blog post like this and save it in a post.json
file:
Our API code references this schema in a middleware that will return a 422
reponse with a list of errors before the main body of the endpoint is executed. The name of the schema is taken from the filename.
var express = ;var RestSpec = ;var schema = RestSpec; // look for spec files in current directoryvar storage = ; var app = ; app; // make API documentation accessible at `/docs/` URL. RestSchema app;console;
POSTing malformed request will make API return 422
with the reason:
$ curl -XPOST -H "Content-Type: application/json" -d '{"title": "My first post", "kittens": true}' http://localhost:3000/posts
Note the explorer
bit in the api code:
RestSchema
It maps dynamically generated documentation to /docs
.