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
class BackfillUsersFullName < ActiveRecord::Migration[7.1] disable_ddl_transaction! BATCH_SIZE = 5_000
How to backfill a column safely in Rails
migrations
batching
backfill
Intermediate
7 steps
ruby
class ProjectsController < ApplicationController def new @project = current_account.projects.build load_form_collections
The new/create pattern in a Rails controller
mvc
strong-parameters
tenant-scoping
Intermediate
7 steps
go
type CreateUserInput struct { Name string `json:"name" binding:"required,min=2,max=64"` Email string `json:"email" binding:"required,email"` Password string `json:"password" binding:"required,min=8"`
Turning Gin validation errors into JSON
validation
request-binding
error-handling
Intermediate
9 steps
ruby
class Membership < ApplicationRecord belongs_to :organization belongs_to :user
Enforcing scoped uniqueness in Rails
validations
uniqueness
callbacks
Intermediate
8 steps
ruby
class WebhookSignatureConstraint def initialize(provider) @provider = provider end
Verifying webhook signatures with Rails routing constraints
routing constraints
hmac
webhooks
Advanced
7 steps
ruby
module UniqueJob extend ActiveSupport::Concern class_methods do
Deduplicating Active Job enqueues in Rails
concurrency
idempotency
caching
Advanced
9 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.