Table of Contents
Building a RESTful API with Ruby on Rails is a powerful way to create backend services for web and mobile applications. This tutorial guides you through the process of setting up your first API, from installation to testing.
Prerequisites
- Ruby installed on your system
- Ruby on Rails framework installed
- Basic understanding of Ruby and Rails
- PostgreSQL or another database set up
Setting Up a New Rails Project
Start by creating a new Rails project with the –api flag to generate an API-only application:
rails new my_api --api
Navigate into your project directory:
cd my_api
Generating a Resource
Create a resource, for example, a “Post” model with title and content fields:
rails generate resource Post title:string content:text
Run the migrations to create the database table:
rails db:migrate
Configuring Routes
Open config/routes.rb and add:
Rails.application.routes.draw do
resources :posts
end
Creating the Controller
Generate the controller:
rails generate controller Posts
Open app/controllers/posts_controller.rb and define actions:
class PostsController < ApplicationController
def index
posts = Post.all
render json: posts
end
def show
post = Post.find(params[:id])
render json: post
end
def create
post = Post.new(post_params)
if post.save
render json: post, status: :created
else
render json: post.errors, status: :unprocessable_entity
end
def update
post = Post.find(params[:id])
if post.update(post_params)
render json: post
else
render json: post.errors, status: :unprocessable_entity
end
def destroy
post = Post.find(params[:id])
post.destroy
head :no_content
end
private
def post_params
params.require(:post).permit(:title, :content)
end
Testing Your API
Use tools like Postman or cURL to test your endpoints. For example, to test the index action:
curl -X GET http://localhost:3000/posts
To create a new post:
curl -X POST -H "Content-Type: application/json" -d '{"post": {"title": "My First Post", "content": "Hello World"}}' http://localhost:3000/posts
Conclusion
Congratulations! You have created your first RESTful API with Ruby on Rails. You can now expand this API by adding authentication, pagination, and other features to suit your application’s needs.