0
0
Ruby on Railsframework~30 mins

API versioning in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
API Versioning in Rails
📖 Scenario: You are building a simple Rails API for a bookstore. You want to support multiple versions of your API so that you can improve it later without breaking existing clients.
🎯 Goal: Create a basic Rails API with two versions: v1 and v2. Each version will have a BooksController with an index action that returns a list of books. The v2 version will add a new field to the book data.
📋 What You'll Learn
Create a Book model with title and author attributes
Set up API versioning using namespaces v1 and v2 in routes
Implement BooksController in both versions with an index action
In v1, return title and author for each book
In v2, return title, author, and a new published_year field
💡 Why This Matters
🌍 Real World
API versioning is essential when you want to improve or change your API without breaking existing clients. Many companies use versioning to support old and new app versions simultaneously.
💼 Career
Understanding API versioning in Rails is important for backend developers working on web services, ensuring smooth upgrades and backward compatibility.
Progress0 / 4 steps
1
Create the Book model with attributes
Create a Rails model called Book with string attributes title and author. Add a migration to create the books table with these columns.
Ruby on Rails
Need a hint?

Use rails generate model Book title:string author:string to create the model and migration.

2
Set up API versioning namespaces in routes
In config/routes.rb, create two namespaces: v1 and v2. Inside each namespace, add a resource route for books with only the index action.
Ruby on Rails
Need a hint?

Use namespace :v1 do ... end and namespace :v2 do ... end blocks in routes.

3
Implement BooksController with index action for v1
Create V1::BooksController with an index action that fetches all books and renders JSON with only title and author fields.
Ruby on Rails
Need a hint?

Use render json: books.as_json(only: [:title, :author]) to limit fields.

4
Implement BooksController with index action for v2 with extra field
Create V2::BooksController with an index action that fetches all books and renders JSON with title, author, and published_year fields. Add published_year as a string attribute to the Book model migration.
Ruby on Rails
Need a hint?

Remember to add published_year column to the books table and include it in the JSON response.