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
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
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
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-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.