Naya Bonbo Naya Bonbo - 4 months ago 25
reST (reStructuredText) Question

REST API versioning - why aren't models versioned

I've been reading up on all the approaches to version REST APIs. In almost all implementations, controllers and views are versioned, however models are not.

To give the rails example, controllers are organized as:

# app/controllers/api/v1/events_controller.rb
class Api::V1::EventsController < Api::ApiController


Corresponding views as put in at different versioned directories as well. Why don't we version models? Is it because we expect our model (underlying database schema) to not change as the API evolves? What happens when I rename a column name in the database and need a new model to account for that?

max max

Models are part of the internals of an application, not its public API. When versioning the key is that the input / output does not deviate.

Maintaining different versioned data in the database - eg data that belongs to different versions of an API is not particularly appealing or practical.

So instead you would use adapters / serializers to adapt the input / output to a particular version of your API while the internals run at the current version.

Lets say you have published an API v 1 in a hurry:

GET api/v1/users/:id
  username (String)
  first_name (String)
  lastname (String)

After the release you realize that the naming is inconsistent. So you would create a migration which renames lastname to last_name.

So API version 2 would have the following signature:

GET api/v2/users/:id
  username (String)
  first_name (String)
  last_name (String)

But this should break a test for the API v 1 since the response no longer contains lastname.

So to fix it we would create something like:

Api::V1::UserSerializer < ActiveModel::Serializer
  attributes :username, :first_name, :lastname

  def lastname