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
end
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?
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:
After the release you realize that the naming is inconsistent. So you would create a migration which renames
lastname
tolast_name
.So API version 2 would have the following signature:
But this should break a test for the
API v 1
since the response no longer containslastname
.So to fix it we would create something like:
Models typically are closely aligned with the database schema. Typically the database is a canonical data store shared by all versions of APIs, hence it does not make much sense to version the models.
Plus, in Rails applications, often the bulk of buisness logic resides in the models. Versioning models would require either replicating the logic or addition of another layer of abstraction which introduces maintenance overhead.
No. Database schema can and does change very often.
You don't introduce a model to account for schema changes. You adapt the existing model to accomodate the change, and then modify the implementations of prior APIs so the previous version clients continue getting the response in the same format as they expected before.
Since this mapping of your buisness entities (models) to API responses, happens in controllers (or serializers, or json templates - depending on your preferred implementation) -- these parts of your application will have to be modified to ensure backward compatibility.