0
0
RailsHow-ToBeginner · 4 min read

How to Use Rails API Mode in Ruby on Rails

To use rails api mode, create a new Rails project with rails new my_api --api. This sets up a lightweight app optimized for JSON APIs by skipping views, assets, and session middleware.
📐

Syntax

The main command to start a Rails API-only app is:

  • rails new app_name --api: Creates a new Rails project optimized for API use.

This mode configures Rails to skip frontend features like views and assets, and includes only middleware needed for APIs.

bash
rails new my_api --api
💻

Example

This example shows how to create a simple API-only Rails app that responds with JSON data.

It demonstrates the minimal setup and a controller returning JSON.

bash
rails new simple_api --api
cd simple_api
# Generate a controller
rails generate controller Greetings index --skip-assets --skip-template-engine

# Edit app/controllers/greetings_controller.rb to:
class GreetingsController < ApplicationController
  def index
    render json: { message: "Hello from Rails API mode!" }
  end
end

# Add route in config/routes.rb:
Rails.application.routes.draw do
  get '/greet', to: 'greetings#index'
end

# Start server
rails server
Output
When you visit http://localhost:3000/greet you get: {"message":"Hello from Rails API mode!"}
⚠️

Common Pitfalls

Some common mistakes when using Rails API mode:

  • Expecting views or HTML responses: API mode skips views, so you must render JSON explicitly.
  • Missing middleware for sessions or cookies: API mode disables these by default; add them back if needed.
  • Trying to use asset pipeline or frontend helpers: These are not included in API mode.

To fix missing middleware, add them manually in config/application.rb.

ruby
## Wrong: Trying to render a view in API mode
class WelcomeController < ApplicationController
  def home
    # This will fail because views are disabled
  end
end

## Right: Render JSON explicitly
class WelcomeController < ApplicationController
  def home
    render json: { welcome: "Hello API" }
  end
end
📊

Quick Reference

Summary tips for Rails API mode:

  • Use rails new app_name --api to create API-only apps.
  • Render JSON responses explicitly in controllers.
  • Add middleware manually if you need sessions or cookies.
  • Skip frontend features like views, helpers, and assets.
  • Use tools like ActiveModelSerializers or Jbuilder for JSON formatting.

Key Takeaways

Create API-only apps with `rails new app_name --api` for a lightweight JSON backend.
API mode disables views and frontend middleware; always render JSON explicitly.
Add back middleware like sessions only if your API needs them.
Use JSON serializers or builders to format API responses cleanly.
Rails API mode is ideal for backend services serving JSON to frontend apps or mobile clients.