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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Namespacing controllers under modules like Api::V2 lets you version an API without breaking existing clients.
- 2Rendering with explicit serializers keeps JSON shape decoupled from your models and consistent across actions.
- 3Building records through associations like current_user.articles scopes ownership and enforces authorization implicitly.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-versioned-json-api-controller-in-rails-explained-ruby-6dbe/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.