Self API
Simple, self-documenting and self-testing API helper for Node.js.
Works with express, restify and scout camp.
Note: This is not a routing engine. You need one of the above to build a working API. (Self API just provides an easier way for you to develop, document and test web APIs.)
Try Self API
Install it:
npm install selfapi
Use it:
var selfapi = ; // API root resource, mounted at '/api' on your server app:var api = ; api; // API sub-resource, mounted at '/api/items' on your server app:var items = api; items;
Your API can self-document:
> console.log(api.toMarkdown());# My API ## Show API version `GET /api` Show the latest API version currently supported. ### Example request: GET /api ### Example response: Status: 200 OK v1.0 # Items ## Add a new item `POST /api/items` Create a new item and add it to our collection. ### Example request: POST /api/items {"name":"My Item"} ### Example response: Status: 201 Created {"status":"Created","item":{"name":"My Item"}}…
… and self-test, using its own examples:
> api.test('http://localhost:8080');Results: 2/2 tests passed.
Note: When testing the API, all your routes should have examples
, which
might be empty. This is to ensure all routes are documented and you are well
aware some endpoints are lacking tests.
Note: You can also document and test each API resource individually, but remember to provide the correct base path like so:
> console.log(items.toMarkdown('/api'))## Add a new item `POST /api/items` Create a new item and add it to our collection… > items.test('http://localhost:8080/api')Results: 1/1 test passed.
Getting started
Create your API using express:
var express = ;var selfapi = ; // Create your server app:var app = ; // Create your API, mounted at '/api' on your server app:var api = ; // This does exactly the same thing:var api = ; // This too:appapi = selfapi;var api = app; // This too:var router = express;app;var api = ;
Write request handlers the same way you would in express, just with a bit more info:
// This will register some metadata, and export the handler function to express.api;
Create API sub-resources when it seems useful.
Note: They're basically just a common prefix for similar request handlers (a bit like a very lightweight express Router), but they'll create dedicated documentation sections, and can be tested individually.
// Create an API sub-resource, mounted at '/api/items' on your server app:var items = api; // This does the same thing:var items = ; // This too:var items = ; // … you get the idea.
For more examples of how to use Self API, please have a look at the tests.