api-template
Define and build your project's api with mocked data.
api-template is a lightweight api generator, it uses mustache.js and datafixture.js to build from simple hardcoded server responses up to complex dynamically generated api results.
It gives you enough control to:
- map a route to a source
- set the reponse's http headers (optional)
- different types of response avaiable:
- hardcoded (static)
- templated response (mustache + json)
- dynamic templated response (mustache + json + datafixture)
Getting Started
Dependencies
How it works
You will need to create a json file with your API's definition. The file will need to have the following structure:
example api.json
file:
Example implementation:
var express = ;var path = ;var http = ;var api = ; var app = ; app; // register your apiapi; http;
api hash
api
: collection of api path definitions
the api
collection exppects a hash of objects, each key
is the actual path
that expressjs will match against each service created.
path definition
"/api/home":
path's definition key
"/api/home"
-> will be accesed at http://localhost:3000/api/home
header definition
"header": ,
This is optional, if defined, its a hash of header settings, the object will get
passed directly to express's response.set()
method, more info at:
http://expressjs.com/api.html#res.set.
response definition
The response object where the magic happens, it can be defined in multiple ways:
1 - most simple:
This will tell api-template
to respond with the content of the file being
mapped to. Currenty only supports text based files.
"response": "./api/home.json"
2 - rendered teamplte with json source:
Response will be the result of the content of "data"
json file passed into
mustache.render()
.
"response":
3 - rendered teamplte with dynamic json source:
Same process as with option 2, the difference is that the json source will now be
passed through datafixture.js. This
is done by setting the flag "dynamic"
to true
:
"response":
url routing and query paramters
Because we are using ExpressJS we can generate dynamic routes.
Some examples:
/home
=> http://localhost:3000/home/book/:bookId
=> http://localhost:3000/book/99921-58-10-7/author/:authorId/books/new
=> http://localhost:3000/author/darek/books/new
ExpressJS passes a request object for each service, this one has all information passed into the url, including route variables and query variables. This object is passed into the JSON Object that is passed into a template, when template is defined. Giving you full access to it to be used in any way you want on the template.
Example of its implementation:
route definition:
"/api/isbn/:isbn":
file: ./api/isbn.template
Making a call to http://localhost:3000/api/isbn/SOME-ISBN-NUMBER
its output
could look like:
Next Steps:
- complete RESTful support.
- support for nested sources, this will allow each service to share JSON results