REST APIs with Node Tastypie - Part 2


ast time we took a look at setting up a pretty full featured REST api centered around Mongoose. However, sometimes simple is better. Maybe you don't want and/or need all of the extra things that the MongoResource in Tastypie provides. Sometimes you just want to get something, anything working and dump out some data. We don't need paging, caching, filtering, validation, etc. Luckily, Tastypie gives you a dead simple way to do this by simply defining the methods you want to support. Resource methods are defined as <HTTPVERB>_<ACTION>. So a dumb crud resource would look like this:

The Simple Resource

var Resource = require('tastypie').Resource;

var Simple = Resource.extend({  
    get_list: function( bundle ){
        // use the respond method if you
        // want serialization, status code, etc... = { key:'value' }; 
        return this.respond( bundle )
    , get_detail: function( bundle ){
        // or just send a straight response.
        return bundle.res({succes:1}).code( 200 )
    , put_detail: function( bundle ){
        return bundle.res({any:'data you want'}).code( 202 )
    , post_list: function( bundle ){
        var data = bundle.req.payload;
        // do something with the data.
        return bundle.res({any:'data you want'}).code( 201 )
    , delete_detail: function( bundle ){
        return bundle.res().code( 204 )

That is pretty much all there is to it. You can use the respond method on the resource if you would like to have some level of consistency.

Sometimes Simple Is Better

The respond method will take care of Content negotiation, serialization, and set some headers for you. If you want to skip all of that, you can just use the res method on the bundle, which is a hapi reply function.

API Serializer

Although I'm not too keen on the implementation, you can give an Api instance a serializer and let it do the content negotiation, serialization and deserialization for you.

var Api = require('tastypie').Api;  
var Serializer = require('tastypie').Serializer;  
var server = new( require('hapi') ).Server();  
var v1 = new Api('api/v1', {  
    serializer: new Serializer()

v1.use('simple', new Simple());  
server.register( v1, console.log );  

Done! When a serializer is present, the Api instance will inject itself into the request life-cycle and do the heavy lifting. Now you can use reply with plain old JSON objects ( return bundle.res({}) ). Really nice for prototyping or quick iterations with front-end teams.

tastypie REST hapi node