Well you want to create API only app in Rails Right? Creating an API in Ruby on Rails allows your application to communicate with other services, enabling data exchange and integration.

This quick post will teach you the process of building a simple API using Rails, employing straightforward language and a user-friendly approach.

What exactly API is?

If you don't know what API exactly is then API (Application Programming Interface) is a set of rules that lets different software applications communicate with each other.

In the context of web development, an API allows your server to interact with other servers or client applications, such as mobile apps or frontend JavaScript frameworks.

Create a API only Rails app

Open your terminal and run:



rails new my_api --api

The --api flag sets up a Rails application optimized for API-only functionality, excluding unnecessary components like views and assets.

Set up the database

By default, Rails uses SQLite for the database. You can configure a different database like PostgreSQL by modifying the config/database.yml file.

After configuration, create and migrate the database:



rails db:create
rails db:migrate

2. Enable CORS (Cross-Origin Resource Sharing)

Enable CORS to allow external applications to interact with your API, First uncomment and configure the rack-cors gem in your Gemfile.


gem 'rack-cors'

Then, configure it in config/initializers/cors.rb:


     Rails.application.config.middleware.insert_before 0, Rack::Cors do
       allow do
         origins '*'
         resource '*',
           headers: :any,
           methods: [:get, :post, :put, :patch, :delete, :options, :head]
       end
     end

This setup allows any origin to access your API.

Generate a resource

For now we gonna create a Post resource, Run the following command in your terminal create the model, controller, and migration files for the Post resource.


     rails generate resource Post title:string body:text

Run migrations

Apply the database migrations to create the necessary tables.


     rails db:migrate

Set up routes

In config/routes.rb, define routes for your resources.


     Rails.application.routes.draw do
       namespace :api do
         namespace :v1 do
           resources :posts
         end
       end
     end

This setup creates routes like /api/v1/posts.

Implement Controller Actions

Head over to app/controllers/api/v1/postscontroller.rb, define actions to handle requests.


     module Api
       module V1
         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
           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
           end

           def destroy
             post = Post.find(params[:id])
             post.destroy
             head :no_content
           end

           private

           def post_params
             params.require(:post).permit(:title, :body)
           end
         end
       end
     end

These actions handle CRUD operations for the Post resource.

Finally start the Rails server

Now we're done with everything, you can run the server and test your endpoint.:


     rails server

Your API will be accessible at localhost URL should look like this http://localhost:3000.

Use API Clients

Tools like Postman or curl can be used to test your API endpoints by sending HTTP requests and inspecting responses.

That's a wrap up. By following these simple steps, you've set up a basic API in Ruby on Rails.

Now go ahead and test your endpoints integrate this to your front end application like React App.

I hope you learned something, let me know the feedback in the comments below. Thanks.


Comments(0)