0
0
RailsHow-ToBeginner · 4 min read

How to Create API in Rails: Simple Guide with Example

To create an API in Rails, generate a controller with actions that respond with JSON data and define routes using resources in config/routes.rb. Use render json: in controller actions to send JSON responses for API clients.
📐

Syntax

In Rails, an API controller action typically looks like this:

  • def action_name: Defines the action method.
  • render json: object: Sends the object as a JSON response.
  • resources :resource_name: Defines RESTful routes for the resource in config/routes.rb.
ruby
class ItemsController < ApplicationController
  def index
    items = Item.all
    render json: items
  end
end

# In config/routes.rb
Rails.application.routes.draw do
  resources :items, only: [:index]
end
💻

Example

This example shows a simple API that returns a list of items in JSON format when you visit /items.

ruby
class ItemsController < ApplicationController
  def index
    items = [
      { id: 1, name: "Apple", price: 1.2 },
      { id: 2, name: "Banana", price: 0.5 }
    ]
    render json: items
  end
end

# config/routes.rb
Rails.application.routes.draw do
  resources :items, only: [:index]
end
Output
[{"id":1,"name":"Apple","price":1.2},{"id":2,"name":"Banana","price":0.5}]
⚠️

Common Pitfalls

Common mistakes when creating APIs in Rails include:

  • Not setting render json: and accidentally rendering HTML views.
  • Forgetting to restrict routes to only needed actions, exposing unwanted endpoints.
  • Not handling errors or missing records, which can cause server errors.
  • Not using ApplicationController or API-specific base controller for API-only apps.
ruby
class ItemsController < ApplicationController
  # Wrong: renders HTML by default if no render json
  def index
    @items = Item.all
  end

  # Right: explicitly render JSON
  def show
    item = Item.find(params[:id])
    render json: item
  rescue ActiveRecord::RecordNotFound
    render json: { error: "Item not found" }, status: :not_found
  end
end
📊

Quick Reference

Summary tips for creating APIs in Rails:

  • Use render json: object to send JSON responses.
  • Define routes with resources and limit actions with only:.
  • Handle errors gracefully with proper HTTP status codes.
  • Consider using rails new myapp --api to generate an API-only app.

Key Takeaways

Use controller actions with render json to build API responses in Rails.
Define RESTful routes with resources and limit to needed actions.
Handle errors and missing records to avoid server crashes.
Consider generating API-only Rails apps for cleaner API development.
Always test your API endpoints to ensure correct JSON output.