Skip to content

Creating Resources

esatterwhite edited this page Apr 11, 2015 · 1 revision

The REST paradigm talks a bout data as a resource. Like wise, tastypie provides a resource class which a standard way of defining a new data resource. The resource class is the primary way to expose additional functionality though URIs. A Resource is best thought of a data model for your API. If you were making a blog, you might create a Post resource. The simple example would be to create a C.R.U.D. API for posts.

As a convention, tastypie maps the HTTP verbs to internal methods names. GET /post gets mapped to get_list, GET /post/:id gets mapped to get_detail. The same applied for all of the HTTP verbs. If the method isn't defined, The resource will return a 405.

Basic CRUD Resource

Here is a basic CRUD setup for a default resource

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

// enpoints will return {title:'', content:'', tags:[]}
var PostResource = Resource.extend({
 fields:{
    title:{type:'char'},
    content:{type:'char'},
    tags:{type:'array'}
 },
 // GET /post
 get_list: function( bundle ){
     that = this;
     some.db.query(function(err, objects ){
        bundle.data = objects
        that.respond( bundle )
     })
 },

 // GET /post/{pk}
 get_detail: function( bundle ){
    var id = bundle.req.params.pk;
    var that = this;

    some.db.query(id, function( err, object ){
        bundle.data = object;
        that.respond( bundle );
    });
 },

 // PUT /post/{pk}
 put_detail: function( bundle ){},

 // POST /post
 post_list: function( bundle ){},

 // DELETE /post/{pk}
 delete_detail: function(bundle){},

 // PATCH /post/{pk}
 patch_detail: function(bundle){}
});

Hooking up a resource

var tastypie = require('tastypie');
var Api = tastypie.Api
var hapi = require('hapi')
var PostResource = require('./resources/post');
var api;
var server;

server = new hapi.Server();
server.connection({port:process.env.PORT || 2000 });

api = new Api('api/v1')
api.use('post', new PostResource());

server.register( [api] , function(e){
    app.start(function(){
    console.log('server is ready')
});
Clone this wiki locally