TL;DR: Crafting an API. Need different fields for different versions. Teach me, wise ones.
I'm currently trying to figure out the best way to craft a versioned API. That is to say, I wish to have a URL of /api/v1/projects.json
that would show a list of projects with a bunch of fields and api/v2/projects.json
to show a list of projects with separate fields.
I've been thinking about this problem for about 15 minutes which probably means it's all wrong. At the moment I've got this in my app/models/project.rb
file:
def self.api_fields
{
:v1 => ["name"],
:v2 => ["name", "tickets_count"]
}
end
Then I can use this in my API controllers (api/v1/projects_controller.rb
) like this:
def index
respond_with(Project.all(:select => Project.api_fields[:v1]))
end
This is great and works as I'd like it to, but there's probably a better way about it. That's your task! Share with me your mountains of API-crafting wisdom.
Bonus points if you come up with a solution that will also allow me to use methods for instances of a model's object, such as a tickets_count
method on a Project
method.