0
0
Ruby on Railsframework~5 mins

Why Rails API mode exists

Choose your learning style9 modes available
Introduction

Rails API mode exists to help build fast and simple backends that only send data, not full web pages.

When you want to create a backend that serves data to a mobile app.
When building a single-page app that handles its own user interface.
When you want a lightweight server that only provides JSON responses.
When you want to separate frontend and backend development clearly.
When you need to build an API for other services or clients to use.
Syntax
Ruby on Rails
rails new my_api --api

This command creates a new Rails app optimized for API-only use.

It skips views, helpers, and assets by default to keep things simple.

Examples
Creates a new Rails app named blog_api in API mode.
Ruby on Rails
rails new blog_api --api
Creates an API-only Rails app with PostgreSQL as the database.
Ruby on Rails
rails new shop_backend --api --database=postgresql
Sample Program

This example shows a minimal Rails API app setup. The config.api_only = true line tells Rails to run in API mode. The controller inherits from ActionController::API which is lighter than the full controller. The route returns a JSON message.

Ruby on Rails
# config/application.rb
require_relative 'boot'
require 'rails/all'

Bundler.require(*Rails.groups)

module MyApi
  class Application < Rails::Application
    config.load_defaults 7.0
    config.api_only = true
  end
end

# app/controllers/welcome_controller.rb
class WelcomeController < ActionController::API
  def index
    render json: { message: 'Hello from API mode!' }
  end
end

# config/routes.rb
Rails.application.routes.draw do
  get '/', to: 'welcome#index'
end
OutputSuccess
Important Notes

API mode disables views and assets to speed up response time.

You can still add middleware if you need sessions or cookies.

Use API mode when you only want to serve JSON or XML data.

Summary

Rails API mode is for building backends that only send data, not full web pages.

It creates a lightweight app by skipping unnecessary parts like views and assets.

Use it when building APIs for mobile apps, SPAs, or other services.