
In today’s fast-moving web development landscape, building a Rails API is a powerful and reliable approach for powering mobile apps, frontend frameworks, and third-party integrations. Ruby on Rails includes a robust set of tools that make Rails API development feel almost effortless. It enables developers to create clean routes, return JSON responses, and scale backend logic with confidence. Whether you’re building a backend for a single-page app or a distributed microservice, a Rails API offers a seamless and efficient development experience.
In this post, we’ll walk through the process of building a simple API using Rails. You’ll learn:
- Setting up an API-only Rails app
- Handling API routing effectively
- Returning JSON responses from controllers
- Following best practices for scalability
Why Building APIs with Rails Is a Smart Choice
Rails, known for its convention-over-configuration approach, has matured into a powerful API development framework. With --api
mode, Rails strips away the view layer and focuses purely on backend functionality, making it lightweight and faster for API-first applications.
Benefits:
- Easy JSON rendering
- RESTful routing support out of the box
- Strong ActiveRecord integration
- Fast development cycle
Step 1: Create a Rails API-Only Project
To start, generate a new Rails app in API-only mode:
rails new blog_api --api
cd blog_api
As a result, this creates a Rails app optimized for APIs — no views, helpers, or asset pipeline.
Step 2: Define Models for Your Rails API
Let’s create a Post
model with title
and content
:
rails generate model Post title:string content:text
rails db:migrate
For example, you can seed some data like this:
# db/seeds.rb
Post.create([
{ title: "Getting Started with Rails API", content: "Learn how to set up your API-only Rails app." },
{ title: "Understanding JSON Rendering", content: "Master JSON responses in Rails controllers." }
])
rails db:seed
Step 3: Routing in a Rails API Project
Open config/routes.rb
and define the routes:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :posts, only: [:index, :show, :create]
end
end
end
Moreover, using namespaced routes (e.g., /api/v1/posts
) helps you version your API cleanly.
Step 4: Build JSON Controllers in Your Rails API
Now, generate a controller inside your versioned API path:
mkdir -p app/controllers/api/v1
touch app/controllers/api/v1/posts_controller.rb
Here’s an example PostsController
:
module Api
module V1
class PostsController < ApplicationController
def index
posts = Post.all
render json: posts, status: :ok
end
def show
post = Post.find(params[:id])
render json: post, status: :ok
rescue ActiveRecord::RecordNotFound
render json: { error: "Post not found" }, status: :not_found
end
def create
post = Post.new(post_params)
if post.save
render json: post, status: :created
else
render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
end
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
end
end
What’s happening here?
render json:
automatically serializes Ruby objects to JSON.- Consequently, status codes make the Rails API more reliable for consumers.
- Strong params ensure only permitted data is accepted.
Step 5: Testing the Rails API with curl and Postman
Here are some quick commands to test:
- Get all posts:
curl http://localhost:3000/api/v1/posts
- Get a single post:
curl http://localhost:3000/api/v1/posts/1
- Create a new post:
POST http://localhost:3000/api/v1/posts
"Content-Type: application/json"
'{"post": {"title": "New Post", "content": "This is my new blog post."}}'
Bonus: Best Practices for Building APIs with Rails
- Use Jbuilder or ActiveModelSerializers if you want to control the structure of your JSON.
- Paginate large datasets using gems like
kaminari
orpagy
. - Add authentication using gems like Devise. We explain how to integrate it in our Rails Authentication with Devise guide.
- Document your Rails API using tools like rswag or [Swagger UI].
Conclusion
With just a few commands and conventions, building APIs with Rails becomes a seamless experience. If you’re new to the framework, check out our Getting Started with Ruby on Rails guide.Ruby on Rails offers a powerful foundation to develop production-ready JSON APIs quickly and efficiently. Whether you’re creating a backend for React, Angular, or a mobile app, Rails provides clean routing, structured JSON responses, and rapid development features that scale with your project’s needs.
If you’re planning to create an API-first product or integrate with third-party services, building APIs with Rails is a smart, reliable, and future-proof choice.
Looking for more Rails guides? Check out SaasTrail’s advanced Rails guides for practical tips and advanced development patterns.