ruby
39 lines · 7 steps
Building a JSON:API endpoint in Rails
A versioned API controller that paginates, eager-loads, and serializes articles while avoiding N+1 queries.
Explained by
highlit
1class Api::V1::ArticlesController < Api::V1::BaseController
2 def index
3 articles = Article
4 .published
5 .includes(:author, :categories, comments: :author, cover_image_attachment: :blob)
6 .order(published_at: :desc)
7 .page(params[:page])
8 .per(25)
9
10 render json: ArticleSerializer.new(
11 articles,
12 include: %i[author categories comments comments.author],
13 meta: pagination_meta(articles)
14 ).serializable_hash
15 end
16
17 def show
18 article = Article
19 .includes(:author, :categories, { comments: %i[author reactions] })
20 .find(params[:id])
21
22 render json: ArticleSerializer.new(
23 article,
24 include: %i[author categories comments comments.author comments.reactions]
25 ).serializable_hash
26 end
27
28 private
29
30 def pagination_meta(scope)
31 {
32 current_page: scope.current_page,
33 next_page: scope.next_page,
34 prev_page: scope.prev_page,
35 total_pages: scope.total_pages,
36 total_count: scope.total_count
37 }
38 end
39end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Chaining includes with nested hashes preloads deep associations in one pass, sidestepping N+1 queries.
- 2Pagination metadata belongs in a reusable helper so multiple actions return a consistent response shape.
- 3A serializer's include option controls exactly which related records appear, keeping payloads intentional.
Related explainers
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 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-json-api-endpoint-in-rails-explained-ruby-1cca/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.