Build Rails 5 API (Part 2)
Versioning Your API
Before releasing your API, you should consider implementing versioning. Versioning helps your API up into multiple version namespaces, such as v1 and v2. It will be easier to maintain and build higher versions of your API as well as making URL friendly (Eg: http://api.myapi.com/v1/books).
Ok, lets change app's structure like this:
app/controllers/ |-- api | |-- V1 | |-- books_controller.rb |-- application_controller.rb
Add namespace to route
Rails.application.routes.draw do scope module: :api do namespace :v1 do resources :books end end end
Update books controller
# app/controllers/api/V1/books_controller.rb module Api module V1 class BooksController < ApplicationController def index render json: Book.all end end end end
Now you can access http://localhost:3000/v1/books. If you want to implement API v2. Just
- create a copy of V1 folder and name it V2
- Add/Update Enpoints
- Update route
.
That's it!