Published on

Building an API in Ruby on Rails

Authors
  • Name
    Twitter

In this blog post, we'll explore how to build a robust API using Ruby on Rails, one of the most popular web frameworks for building full-featured web applications.

Setting Up Your Rails Project

Before we start building our API, let's set up a new Rails project. Open your terminal and run the following command:

rails new my_api --api

The --api flag sets up a Rails application with a slimmed-down set of middleware suitable for building APIs.

Creating a Resource

Let's create a simple resource called Article. Run the following command to generate the model, controller, and migration:

rails generate scaffold Article title:string body:text

This command generates the necessary files for our Article resource, including routes, model, controller, and views. Since we are building an API, we can remove the generated views.

Run the migration to create the articles table in your database:

rails db:migrate

Configuring Routes

Open the config/routes.rb file and modify it to use only the necessary routes for our API:

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :articles, only: [:index, :show, :create, :update, :destroy]
    end
  end
end

This sets up our routes under the /api/v1 namespace, following RESTful conventions.

Creating the Controller

Open the generated controller file app/controllers/api/v1/articles_controller.rb and update it as follows:

module Api
  module V1
    class ArticlesController < ApplicationController
      before_action :set_article, only: [:show, :update, :destroy]

      # GET /api/v1/articles
      def index
        @articles = Article.all
        render json: @articles
      end

      # GET /api/v1/articles/:id
      def show
        render json: @article
      end

      # POST /api/v1/articles
      def create
        @article = Article.new(article_params)
        if @article.save
          render json: @article, status: :created, location: api_v1_article_url(@article)
        else
          render json: @article.errors, status: :unprocessable_entity
        end
      end

      # PATCH/PUT /api/v1/articles/:id
      def update
        if @article.update(article_params)
          render json: @article
        else
          render json: @article.errors, status: :unprocessable_entity
        end
      end

      # DELETE /api/v1/articles/:id
      def destroy
        @article.destroy
      end

      private

      def set_article
        @article = Article.find(params[:id])
      end

      def article_params
        params.require(:article).permit(:title, :body)
      end
    end
  end
end

Adding Validations

To ensure data integrity, let's add some validations to our Article model. Open app/models/article.rb and update it as follows:

class Article < ApplicationRecord
  validates :title, presence: true, length: { maximum: 100 }
  validates :body, presence: true
end

Testing the API

Start the Rails server with the following command:

rails server

You can use tools like Postman or cURL to test your API endpoints.

List all articles:

GET http://localhost:3000/api/v1/articles

Show a specific article:

GET http://localhost:3000/api/v1/articles/:id

Create a new article:

POST http://localhost:3000/api/v1/articles
Content-Type: application/json

{
  "article": {
    "title": "New Article",
    "body": "This is the body of the new article."
  }
}

Update an existing article:

PUT http://localhost:3000/api/v1/articles/:id
Content-Type: application/json

{
  "article": {
    "title": "Updated Article",
    "body": "This is the updated body of the article."
  }
}

Delete an article:

DELETE http://localhost:3000/api/v1/articles/:id

Adding Authentication (Optional)

For a more secure API, you might want to add authentication. One popular gem for this is devise_token_auth. Follow the devise_token_auth documentation to add user authentication to your API.

Conclusion

Building an API with Ruby on Rails is straightforward and powerful. By following RESTful conventions and leveraging Rails' built-in features, you can create a robust API that can serve as the backend for web and mobile applications. Happy coding!