In Rails 8.1, which ActionController::Base features does ActionController::API leave out, and how do you add one back?
answer
- MODULES list, a subset of Base's
- no layouts, helpers, cookies or flash
- no forgery protection or respond_to
- missing render means 204 No Content
- include ActionController::MimeResponds
basics
~10 sActionController::API drops layouts, helpers, respond_to, cookies, flash, forgery protection and the HTTP authentication helpers, and an action without render answers 204. Add a feature back by including its module, such as ActionController::MimeResponds, in ApplicationController.
solid answer
~30 s`ActionController::API` includes a fixed `MODULES` list that is a subset of `ActionController::Base`'s. It keeps rendering (`render json:`), redirects, `before_action`, `rescue_from`, strong parameters, `stale?` and `fresh_when`, `rate_limit`, caching and `send_data`. It leaves out `ActionView::Layouts`, `Helpers`, `MimeResponds` (`respond_to`), `Cookies`, `Flash`, `RequestForgeryProtection`, `AllowBrowser`, the CSP and permissions-policy helpers, and the Basic, Digest and Token HTTP authentication helpers. It also swaps `ImplicitRender` for `BasicImplicitRender`, so an action that never renders answers `204 No Content` instead of looking for a template. To get a feature back you `include` its module, for example `include ActionController::MimeResponds` in `ApplicationController`; `ActionController::Cookies` additionally needs the cookies middleware.
code
ruby · 11 linesclass Api::V1::WorkoutsController < ApplicationController
def update
workout = Workout.find(params.expect(:id))
workout.update!(params.expect(workout: [:distance_km, :duration_s]))
# no render: ActionController::API answers 204 No Content
end
def show
render json: Workout.find(params.expect(:id))
end
endgo deeper
Remember the headline gaps: no layouts or views, no cookies or flash, no forgery protection, no respond_to.
Explain BasicImplicitRender's 204 fallback and how including a module, plus its middleware, restores a feature.
Spot the silent-204 bug in review and decide which modules an API base controller really needs, keeping the list explicit.
Judge when a shared API base controller should carry auth, error and rate-limit policy for every version versus per-namespace bases.
## Two controller bases, one parent Every Rails controller ultimately descends from **`ActionController::Metal`**, a minimal Rack endpoint that knows how to dispatch to an action and hold a request and response. On top of it Rails builds two ready-made bases by including a list of feature modules: - **`ActionController::Base`** for apps that render HTML to browsers. - **`ActionController::API`** for apps that answer with data. Both classes define a `MODULES` constant and include every entry. API's list is shorter, so its controllers are lighter and carry fewer callbacks and helpers into every request. ## What API keeps | Module | What it gives an API controller | |---|---| | `Renderers::All`, `ApiRendering` | `render json:`, `render xml:` and plain renders | | `Redirecting`, `UrlFor` | `redirect_to`, URL helpers | | `ConditionalGet` | `stale?`, `fresh_when`, `expires_in`, `head` | | `StrongParameters` | `params.expect`, `permit` | | `RateLimiting` | `rate_limit to:, within:` | | `Caching` | fragment cache support for the controller | | `DataStreaming` | `send_file`, `send_data` | | `AbstractController::Callbacks` | `before_action` and friends | | `Rescue` | `rescue_from` | | `ParamsWrapper`, `Instrumentation`, `Logging`, `DefaultHeaders` | wrapped JSON params, notifications, logs, default headers | ## What API leaves out Compared with `Base`, these modules are absent: - **Views:** `ActionView::Layouts`, `Helpers`, `AbstractController::Translation`, `AbstractController::AssetPaths`, `FormBuilder`, `Streaming`, `EtagWithTemplateDigest`. - **Format negotiation:** `MimeResponds`, so `respond_to` is undefined. - **Browser state:** `Cookies` (the `cookies` helper), `Flash` and `EtagWithFlash`. - **Browser security:** `RequestForgeryProtection` (`protect_from_forgery`), `ContentSecurityPolicy`, `PermissionsPolicy`, `AllowBrowser`. - **HTTP authentication helpers:** `HttpAuthentication::Basic::ControllerMethods`, `Digest::ControllerMethods` and `Token::ControllerMethods`. - **Parameter encoding:** `ParameterEncoding`, which lets an action declare non-UTF-8 parameters. - **Implicit template rendering:** `ImplicitRender` is replaced by `BasicImplicitRender`. ## The 204 trap `BasicImplicitRender#default_render` is a single line: `head :no_content`. So in a plain API app, an action that forgets to call `render` or `head` returns **204 No Content** with an empty body. The scaffold's `destroy` action relies on this on purpose; an `update` that forgets its `render json:` is a silent bug that clients see as success with no data. `Base` behaves differently: its `ImplicitRender` looks for a template first, raises `ActionController::MissingExactTemplate` for a browser page load without one, and only falls back to 204 for other requests. One gem changes this: the **jbuilder** railtie includes `ActionController::Helpers` and `ActionController::ImplicitRender` into `ActionController::API` when it loads, so an app that uncomments `jbuilder` gets template lookup back: an action with `show.json.jbuilder` renders it implicitly, and a JSON request with no template still gets 204. ## Adding a feature back 1. Find the module in `ActionController::Base::MODULES` or the API guide. 2. `include` it in `ApplicationController` (app-wide) or a single controller. 3. Add any middleware it depends on: `ActionController::Cookies` and `Flash` need `ActionDispatch::Cookies` (and a session store for flash), which `config.api_only` removed. ```ruby class ApplicationController < ActionController::API include ActionController::MimeResponds include ActionController::HttpAuthentication::Token::ControllerMethods end ``` Modules declare their own dependencies, so including one pulls in what it needs at the controller level. For a controller even leaner than API, `ActionController::API.without_modules(:UrlFor, ...)` returns the list minus the ones you name, ready to include into a `Metal` subclass. ## Why not just use Base Inheriting `Base` in an API works, but every request then runs forgery-protection callbacks, flash sweeping and template lookup it never uses, and a missing render on a browser page load raises instead of returning 204. Choosing `API` and adding back two or three modules keeps the surface explicit. ## Catching the silent 204 in tests Because a forgotten `render` produces a valid-looking empty response, request tests are where it surfaces. Assert on the body, not only the status: ```ruby patch api_v1_workout_path(workout), params: { workout: { distance_km: 5 } }, as: :json assert_response :success assert_equal 5.0, response.parsed_body["distance_km"].to_f ``` A test that only checks `assert_response :success` passes on a 204 and hides the bug, since 204 counts as success. ## Choosing what to include back Treat the API base controller as a deliberate list. A typical mobile API adds nothing at all; one that answers both JSON and CSV may add `MimeResponds`; one that accepts static tokens may add `HttpAuthentication::Token::ControllerMethods`. Each module you include also brings its callbacks and helper methods into every action, so prefer including it in a namespace's base controller over `ApplicationController` when only one part of the API needs it.
- Does a controller inheriting ActionController::API still get rescue_from and before_action?Yes. `AbstractController::Callbacks` and `ActionController::Rescue` are both in API's `MODULES` list, so `before_action`, `around_action`, `skip_before_action` and `rescue_from` work exactly as in `Base`. They are included near the end of the list so callbacks and rescue wrap as much of the action as possible.
- Why does an API app that uncomments jbuilder start rendering templates implicitly?The jbuilder railtie runs an `on_load(:action_controller_api)` hook that includes `ActionController::Helpers` and `ActionController::ImplicitRender` into `ActionController::API`, and makes `ApiRendering` include `ActionView::Rendering`. With `ImplicitRender` in place, an action with a matching `.json.jbuilder` template renders it; without one it still falls back to 204.
- ActionController::API has no before_action or rescue_from.
- A missing render in an API action raises ActionView::MissingTemplate.
- respond_to works in API controllers because Renderers::All is included.
- Inheriting ActionController::Base costs nothing extra in a JSON-only app.
- Including ActionController::Cookies alone restores cookies in an api_only app.