guest@websec: ~/websec/r01-rails-api-app — zsh — 100×40 by SaKKo YouTube ENTH

guest@websec ~ % man r01-rails-api-app

A Rails API App

Our backends are Rails in API-only mode: no HTML views, just JSON in and JSON out. This lesson shows what that mode keeps, what it drops, and where everything lives in our projects.

rails new myapp --api gives you a lighter Rails: controllers inherit from ActionController::API, and there are no views, assets, sessions or flash. Everything else (routing, Active Record, jobs, mailers, tests) works the same.

Creating an API-only app

One flag changes the generator. We always use PostgreSQL, because we rely on uuid keys, jsonb and array columns.

What API mode keeps and drops

keptdropped (add back only if you need it)
routing, params, strong parametersviews, layouts, helpers, asset pipeline
render json:, head, status codescookies (ActionController::Cookies)
before_action, rescue_fromsession store and flash messages
Active Record, Active Job, Action MailerCSRF protection (protect_from_forgery)
caching, logging, instrumentationbrowser-only middleware (method override, flash)
Our admin API logs in with an encrypted cookie, so Api::AppController adds one module back: include ActionController::Cookies. Add modules back one at a time, only where they are needed. Don't switch to ActionController::Base.

One request, start to finish

Every lesson in this track zooms in on one box in this picture.

Tour of our project

Click a folder to see what belongs in it, and what doesn’t.

project tourclick a path

Conventions set at boot

A few initializers shape the whole codebase. You will see their effects in every later lesson.

UUID primary keys

# config/initializers/generator.rb
Rails.application.config.generators do |g|
  g.orm :active_record, primary_key_type: :uuid
end

# every create_table(id: :uuid) defaults to uuidv7(), which sorts by time
ActiveSupport.on_load(:active_record) do
  require "active_record/connection_adapters/postgresql_adapter"

  module PostgresUUIDv7Default
    def create_table(table_name, **options, &block)
      if options[:id] == :uuid && !options.key?(:default)
        options[:default] = -> { "uuidv7()" }
      end
      super(table_name, **options, &block)
    end
  end

  ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.prepend(PostgresUUIDv7Default)
end

IDs cannot be guessed by counting (/users/2, /users/3…), and v7 UUIDs still sort roughly by creation time, which keeps indexes efficient.

Our error classes

# config/initializers/app_error.rb
Rails.configuration.to_prepare do
  class AppError < StandardError; end                # 400 bad request
  class AppAuthenticationError < StandardError; end  # 401 not logged in
  class AppPermissionDenied < StandardError; end     # 403 logged in, not allowed
  class AppSoftDeleteError < StandardError; end      # misuse of soft delete
end

Models and services raise these; one place in Api::AppController turns each class into an HTTP status (lesson r06). to_prepare re-runs the block after code reloads in development, so the classes never go stale.

In our real projects these classes carry a short project prefix instead of App. The pattern is what matters: a few named exceptions, mapped to statuses in one place.

Small core extensions

params[:info].to_bool       # "true" / "yes" => true, "false" / "no" => false, nil => false
"some text".mask            # "so***ext"
ENV.fetch("DEBUG", false).to_bool

Query strings are always strings. to_bool (defined on String, NilClass, TrueClass, FalseClass) lets controllers read flags without == "true" everywhere.

Every Ruby file starts with # frozen_string_literal: true. String literals become immutable, which saves allocations and catches accidental mutation.

Check yourself

Which of these is not available in ActionController::API out of the box?

Cookies are a browser concern, so API mode leaves them out. We add ActionController::Cookies back in Api::AppController for the admin login cookie.

A new integration needs a class that talks to the company directory. Where does it go?

It talks to an external system and has no table: that is a service.