ruby 58 lines · 10 steps

Building a versioned JSON API controller in Rails

A namespaced Rails controller serving CRUD actions for articles as serialized JSON with pagination and strong parameters.

Explained by highlit
1module Api
2 module V2
3 class ArticlesController < Api::BaseController
4 before_action :set_article, only: %i[show update destroy]
5 
6 def index
7 articles = Article.published
8 .includes(:author, :tags)
9 .page(params[:page])
10 .per(params[:per_page] || 25)
11 
12 render json: articles,
13 each_serializer: Api::V2::ArticleSerializer,
14 meta: pagination_meta(articles)
15 end
16 
17 def show
18 render json: @article, serializer: Api::V2::ArticleSerializer
19 end
20 
21 def create
22 article = current_user.articles.build(article_params)
23 
24 if article.save
25 render json: article,
26 serializer: Api::V2::ArticleSerializer,
27 status: :created,
28 location: api_v2_article_url(article)
29 else
30 render json: { errors: article.errors }, status: :unprocessable_entity
31 end
32 end
33 
34 def update
35 if @article.update(article_params)
36 render json: @article, serializer: Api::V2::ArticleSerializer
37 else
38 render json: { errors: @article.errors }, status: :unprocessable_entity
39 end
40 end
41 
42 def destroy
43 @article.destroy!
44 head :no_content
45 end
46 
47 private
48 
49 def set_article
50 @article = Article.find(params[:id])
51 end
52 
53 def article_params
54 params.require(:article).permit(:title, :body, :status, tag_ids: [])
55 end
56 end
57 end
58end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Namespacing controllers under modules like Api::V2 lets you version an API without breaking existing clients.
  2. 2Rendering with explicit serializers keeps JSON shape decoupled from your models and consistent across actions.
  3. 3Building records through associations like current_user.articles scopes ownership and enforces authorization implicitly.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a versioned JSON API controller in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code