API Versioning Using Rails Engine
Abstract
API versioning is needed in terms of development. It is often case that the only part of the API changes and remaining part stays the same in the next version. Copy and paste works of course but it is needed to update multiple versions when fixing bugs. Though branching is better than copy and paste, it is tedious and error prone. In this post I explain the way to share code between versions using rails engine.
Methods
Given API v1 provides basic CRUD of user resources.
As you can see, v1 index
API does not provide paging.
Now you decided to provide paging for v2 index
API (which is incompatible
with v1) but the remaining API (show
, create
, update
and destroy
) stays
the same. In this case you can take advantage of rails engine and routes.
The key point is mounting the previous version at the bottom. That way when the request matches the current version routes, it hides the previous version, otherwise it automatically falls back to the previous version.
As you can see below, v2 index
provides paging information. At the same time
show
API (which is internally routed to v1) is also available under /v2
endpoint.
Conclusion
You can share most of the code between versions using rails engine. There are two key points.
- Define routes only you want to override.
- Mount the previous version at the bottom.
The working example is available at github. Thanks for reading, happy hacking!