Building RESTful APIs in Ruby on Rails 8

Biyanka Mani By Biyanka Mani on April 1, 2026
Ruby on Rails RESTful API architecture

Ruby on Rails has long been a developer favourite for building scalable web applications, and with Rails 8, creating robust Ruby on Rails RESTful APIs has become even more streamlined. PIT Solutions helps businesses build secure, high-performance APIs that power modern web and mobile applications. 

In this comprehensive Ruby on Rails API tutorial, we’ll walk you through building modern, production-ready APIs using the latest features and best practices, including Rails API versioning, serializers, and JWT authentication. With the expertise of PIT Solutions, organisations can implement scalable API architectures that support long-term digital growth. 

What Makes a RESTful API in Ruby on Rails?

REST (Representational State Transfer) is an architectural style that uses HTTP methods to perform CRUD operations. A RESTful API should be:

  • Stateless: Each request contains all the information needed to process it. 

  • Resource-based: URLs represent resources, not actions. 

  • HTTP method-driven: GET, POST, PUT, PATCH, DELETE correspond to read, create, update, and delete operations. 

  • JSON-formatted: Responses typically use JSON for data interchange.

Setting Up a Ruby on Rails 8 RESTful API Application

To understand how RESTful APIs work in Rails 8, let’s build a simple Blog API that manages posts.  

Step 1: Generate the Post Model

We start by creating a Post model using the Rails generator:

rails generate model Post title:string content:text author:string published:boolean

This command generates: 

  • A Post model

  • A database migration

  • Schema updates

At this stage, Rails takes care of mapping the database table to Ruby objects using Active Record.

Step 2: API Versioning in Ruby on Rails

Versioning is a crucial best practice in Rails API development. Rails makes this easy using namespaces. 

Instead of placing controllers directly under app/controllers, we create a versioned API structure:

rails generate controller Api::V1::Posts

This results in app/controllers/api/v1/posts_controller.rb .Rails API versioning allows us to:

  • Introduce breaking changes in future versions. 

  • Maintain backward compatibility.

  • Keep APIs organized and scalable. 

Step 3: RESTful CRUD Operations in Rails Controllers

A RESTful controller typically supports CRUD operations using standard HTTP methods.

HTTP Method Endpoint Purpose
GET /api/v1/posts Fetch all posts
GET /api/v1/posts/:id Fetch a single post
POST /api/v1/posts Create a new post
PATCH/PUT /api/v1/posts/:id Update a post
DELETE /api/v1/posts/:id Delete a post

class Api::V1::PostsController < ApplicationController
  before_action :set_post, only: [:show, :update, :destroy]
  def index
    # fetch all posts
  end
  def show
    # fetch a single post
  end
  def create
    # create a new post
  end
  def update
    # update an existing post
  end
  def destroy
    # delete a post
  end
end

Step 4: Using Strong Parameters for API Security

In Rails APIs, strong parameters act as a security layer that controls which attributes are allowed to be written to the database. This can neglect the mass assignment vulnerability for certain admin-only fields.

 

def post_params
  params.require(:post).permit(:title, :content, :author, :published)
end

Step 5: Handling JSON Responses and HTTP Status Codes

In an API-only Rails app:

  • Responses are returned as JSON.
  • Proper HTTP status codes communicate the request's outcome.

Examples include:

  • 200 OK → Successful request
  • 201 Created → Resource created
  • 404 Not Found → Record doesn’t exist
  • 422 Unprocessable Entity → Validation errors

Step 6: Configuring Routes

Define your routes in config/routes.rb within the API namespace and version:

This generates all CRUD URLs for the posts resource within the versioned API namespace, enabling standard RESTful endpoints for creating, reading, updating, and deleting posts.

 


namespace :api do
  namespace :v1 do
    resources :posts
  end
end

Using Serializers for Structured API Responses

Why Not Just Render Models as JSON?

By default, using render json:@posts directly renders all model attributes, exposing the entire database schema in API responses. This tightly couples your API structure to your models, which can result in: 

  • Breaking API responses when database fields change 

  • Inconsistent JSON formats across endpoints

Using JSONAPI:Serializer in Rails

A serializer acts as a presentation layer between your models and API consumers. The jsonapi-serializer gem is popular in Rails API development because it 

  • Follows the JSON: API specification
  • Produces predictable and standardized responses
  • Scales well for large APIs
     

For our Post resource, we create a serializer and include the serializer class in the controller instead of rendering the model directly. This helps to 

  • Keep internal or sensitive fields hidden.
  • Explicitly define exposed attributes.
  • Maintain consistent response structure.

Error Handling Best Practices in Rails APIs

In production APIs, errors should be handled consistently and communicated clearly to the client. Instead of allowing Rails to return default HTML error pages, we explicitly return JSON error responses.

Rails provides rescue_from to catch exceptions and return meaningful JSON responses.

Add this API base controller such that all controllers inheriting from BaseController (making the Application controller inherit from BaseController).Centralized error handling makes APIs predictable, professional, and easier to consume by frontend applications. 

JWT Authentication in Ruby on Rails APIs

Authentication in Ruby on Rails RESTful APIs is commonly implemented using JSON Web Tokens (JWT). Rails API authentication JWTs allow APIs to remain stateless, which aligns perfectly with REST principles.  

Why Authentication Matters in APIs 

Unlike traditional web apps with sessions and cookies, RESTful APIs are stateless. This means each request must authenticate independently, with no server-side session storage. 

While JWT is a general standard, Rails developers typically rely on well-established gems to simplify implementation:  

  • jwt : A low-level gem used to encode and decode tokens. Suitable when you want full control over authentication logic.  

  • devise: A popular authentication framework for Rails that handles user registration, login, and password management.  

  • devise-jwt :An extension of Devise that integrates JWT-based authentication seamlessly into Rails APIs.  

How JWT Works 

  1. User logs in with credentials (email/password).
  2. Server validates and generates a signed JWT token.
  3. Client stores token (usually in localStorage).
  4. Client includes a token in the Authorization header for subsequent requests.
  5. Server verifies the token signature and extracts the user information.

Conclusion

Rails 8 provides everything you need to build production-ready Ruby on Rails RESTful APIs quickly and efficiently. By following REST principles, implementing proper Rails API versioning, using serializers, robust error-handling methods, and adding Rails API authentication JWT, you'll create APIs that are maintainable, scalable, and developer-friendly. 

At PIT Solutions, we specialize in building scalable, secure, and maintainable Ruby on Rails RESTful APIs tailored to your business needs. Whether you require custom API development, enterprise-grade solutions, or integration services, our expert team delivers with precision and modern best practices. 

We also offer comprehensive web application development and enterprise software development solutions to empower your digital transformation and help you leverage the full potential of Rails technology. 

Ready to Build Your Rails API?

Contact PIT Solutions today to get started on your next project. Let our experienced developers help you create powerful Ruby on Rails RESTful APIs with versioning, authentication, and optimized JSON responses that scale with your business.