0
0
Ruby on Railsframework~5 mins

API-only application setup in Ruby on Rails

Choose your learning style9 modes available
Introduction

API-only setup creates a Rails app that only serves data, not web pages. It is faster and simpler for backend services.

When building a backend that only sends JSON data to a frontend app.
When creating a service for mobile apps to get data.
When you want a lightweight server without views or assets.
When your frontend is handled by another framework like React or Vue.
Syntax
Ruby on Rails
rails new app_name --api

This command creates a Rails app optimized for APIs.

It skips views, helpers, and assets by default.

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

This example shows how to create a new API-only Rails app, add a simple controller that returns JSON, and set a route to access it.

Ruby on Rails
# Terminal commands to create and run an API-only Rails app
rails new sample_api --api
cd sample_api
rails server

# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
end

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

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

API-only apps do not include middleware for sessions or cookies by default.

You can add back features if needed by modifying the middleware stack.

Summary

Use rails new app_name --api to create a lightweight backend.

API-only apps focus on JSON responses, no HTML views.

Great for mobile apps or frontend frameworks needing data from Rails.