Class: ActionController::API
Relationships & Source Files | |
Super Chains via Extension / Inclusion / Inheritance | |
Class Chain:
|
|
Instance Chain:
self,
ParamsWrapper ,
Instrumentation ,
Rescue ,
::ActiveSupport::Rescuable ,
::AbstractController::Callbacks ,
::ActiveSupport::Callbacks ,
Logging ,
DefaultHeaders ,
DataStreaming ,
Rendering ,
::AbstractController::Caching ,
::AbstractController::Caching::Fragments ,
::AbstractController::Caching::ConfigMethods ,
Caching ,
StrongParameters ,
ConditionalGet ,
Head ,
Renderers::All ,
Renderers ,
ApiRendering ,
Redirecting ,
::ActiveSupport::Benchmarkable ,
UrlFor ,
::AbstractController::UrlFor ,
::ActionDispatch::Routing::UrlFor ,
::ActionDispatch::Routing::PolymorphicRoutes ,
::AbstractController::Rendering ,
::ActionView::ViewPaths ,
Metal ,
::AbstractController::Base ,
::ActiveSupport::Configurable
|
|
Inherits: |
ActionController::Metal
|
Defined in: | actionpack/lib/action_controller/api.rb |
Overview
API
Controller is a lightweight version of Base
, created for applications that don’t require all functionalities that a complete ::Rails
controller provides, allowing you to create controllers with just the features that you need for API
only applications.
An API Controller is different from a normal controller in the sense that by default it doesn’t include a number of features that are usually required by browser access only: layouts and templates rendering, flash, assets, and so on. This makes the entire controller stack thinner, suitable for API
applications. It doesn’t mean you won’t have such features if you need them: they’re all available for you to include in your application, they’re just not part of the default API
controller stack.
Normally, ApplicationController
is the only controller that inherits from API
. All other controllers in turn inherit from ApplicationController
.
A sample controller could look like this:
class PostsController < ApplicationController
def index
posts = Post.all
render json: posts
end
end
Request, response, and parameters objects all work the exact same way as Base
.
Renders
The default API
Controller stack includes all renderers, which means you can use render :json
and siblings freely in your controllers. Keep in mind that templates are not going to be rendered, so you need to ensure your controller is calling either render
or redirect_to
in all actions, otherwise it will return 204 No Content
.
def show
post = Post.find(params[:id])
render json: post
end
Redirects
Redirects are used to move from one action to another. You can use the redirect_to
method in your controllers in the same way as in Base
. For example:
def create
redirect_to root_url and return if
# do stuff here
end
Adding New Behavior
In some scenarios you may want to add back some functionality provided by Base
that is not present by default in API
, for instance MimeResponds
. This module gives you the respond_to
method. Adding it is quite simple, you just need to include the module in a specific controller or in ApplicationController
in case you want it available in your entire application:
class ApplicationController < ActionController::API
include ActionController::MimeResponds
end
class PostsController < ApplicationController
def index
posts = Post.all
respond_to do |format|
format.json { render json: posts }
format.xml { render xml: posts }
end
end
end
Make sure to check the modules included in Base
if you want to use any other functionality that is not provided by API
out of the box.
Constant Summary
-
MODULES =
# File 'actionpack/lib/action_controller/api.rb', line 115[ AbstractController::Rendering, UrlFor, Redirecting, ApiRendering, Renderers::All, ConditionalGet, BasicImplicitRender, StrongParameters, RateLimiting, Caching, DataStreaming, DefaultHeaders, Logging, # Before callbacks should also be executed as early as possible, so also include # them at the bottom. AbstractController::Callbacks, # Append rescue at the bottom to wrap as much as possible. Rescue, # Add instrumentations hooks at the bottom, to ensure they instrument all the # methods properly. Instrumentation, # Params wrapper should come before instrumentation so they are properly showed # in logs ParamsWrapper ]
::AbstractController::Rendering
- Included
DEFAULT_PROTECTED_INSTANCE_VARIABLES
Redirecting
- Included
Renderers
- Included
Rendering
- Included
::ActiveSupport::Callbacks
- Included
ParamsWrapper
- Included
Class Attribute Summary
Metal
- Inherited
::AbstractController::Base
- Inherited
.abstract? | Alias for AbstractController::Base.abstract. |
.supports_path? | Returns true if the given controller is capable of rendering a path. |
Class Method Summary
-
.without_modules(*modules)
Shortcut helper that returns all the
API
modules except the ones passed as arguments:
Metal
- Inherited
.action | Returns a |
.controller_name | Returns the last part of the controller’s name, underscored, without the ending |
.dispatch | Direct dispatch to the controller. |
.make_response!, | |
.middleware | The middleware stack used by this controller. |
.new, | |
.use | Pushes the given |
::AbstractController::Base
- Inherited
.abstract, | |
.abstract! | Define a controller as abstract. |
.action_methods | A list of method names that should be considered actions. |
.clear_action_methods! | action_methods are cached and there is sometimes a need to refresh them. |
.controller_path | Returns the full controller name, underscored, without the ending Controller. |
.internal_methods | A list of all internal methods for a controller. |
.method_added | Refresh the cached action_methods when a new action_method is added. |
::ActiveSupport::DescendantsTracker
- Extended
Instance Attribute Summary
Instrumentation
- Included
Rescue
- Included
#rescue_handlers, #rescue_handlers?, | |
#show_detailed_exceptions? | Override this method if you want to customize when detailed exceptions must be shown. |
::AbstractController::Callbacks
- Included
::AbstractController::Caching
- self
::AbstractController::Caching::ConfigMethods
- Included
StrongParameters
- Included
#params | Returns a new |
#params= | Assigns the given |
Renderers::All
- Included
Redirecting
- Included
::AbstractController::UrlFor
- Included
::ActionView::ViewPaths
- Included
Metal
- Inherited
#content_type, #headers, #location, #media_type, #middleware_stack, #middleware_stack?, #params, #params=, | |
#performed? | Tests if render or redirect has already happened. |
#request | :attr_reader: request. |
#response | :attr_reader: response. |
#response= | Assign the response and mark it as committed. |
#response_body=, #session, #status |
::AbstractController::Base
- Inherited
#action_name | Returns the name of the action this controller is processing. |
#formats | Returns the formats that can be processed by the controller. |
#performed? | Tests if a response body is set. |
#response_body | Returns the body of the HTTP response sent by the controller. |
Instance Method Summary
Instrumentation
- Included
#redirect_to, #render, #send_data, #send_file, | |
#append_info_to_payload | Every time after an action is processed, this method is invoked with the payload, so you can add more information. |
#cleanup_view_runtime | A hook which allows you to clean up any time, wrongly taken into account in views, like database querying time. |
::ActiveSupport::Rescuable
- Included
#rescue_with_handler | Delegates to the class method, but uses the instance as the subject for rescue_from handlers (method calls, |
::ActiveSupport::Callbacks
- Included
#run_callbacks | Runs the callbacks for the given event. |
DataStreaming
- Included
#send_data | Sends the given binary data to the browser. |
#send_file | Sends the file. |
Rendering
- Included
#render | Renders a template and assigns the result to |
#render_to_string | Similar to |
::AbstractController::Caching
- self
#view_cache_dependencies, | |
#cache | Convenience accessor. |
::AbstractController::Caching::Fragments
- Included
#combined_fragment_cache_key | Given a key (as described in |
#expire_fragment | Removes fragments from the cache. |
#fragment_exist? | Check if a cached fragment from the location signified by |
#read_fragment | Reads a cached fragment from the location signified by |
#write_fragment | Writes |
ConditionalGet
- Included
#expires_in | Sets the |
#expires_now | Sets an HTTP 1.1 |
#fresh_when | Sets the |
#http_cache_forever | Cache or yield the block. |
#no_store | Sets an HTTP 1.1 |
#stale? | Sets the |
Head
- Included
#head | Returns a response that has no content (merely headers). |
Renderers
- Included
#_render_to_body_with_renderer, | |
#render_to_body | Called by |
ApiRendering
- Included
Redirecting
- Included
#redirect_back | Soft deprecated alias for |
#redirect_back_or_to | Redirects the browser to the page that issued the request (the referrer) if possible, otherwise redirects to the provided default fallback location. |
#redirect_to | Redirects the browser to the target specified in |
#url_from | Verifies the passed |
::ActiveSupport::Benchmarkable
- Included
#benchmark | Allows you to measure the execution time of a block in a template and records the result to the log. |
UrlFor
- Included
::AbstractController::UrlFor
- Included
::ActionDispatch::Routing::UrlFor
- Included
#initialize, | |
#route_for | Allows calling direct or regular named route. |
#url_for | Generate a URL based on the options provided, |
#url_options | Hook overridden in controller to add request information with |
#_routes_context, #_with_routes |
::ActionDispatch::Routing::PolymorphicRoutes
- Included
#polymorphic_path | Returns the path component of a URL for the given record. |
#polymorphic_url | Constructs a call to a named RESTful route for the given record and returns the resulting URL string. |
::AbstractController::Rendering
- Included
#render | Normalizes arguments and options, and then delegates to render_to_body and sticks the result in |
#render_to_body | Performs the actual template rendering. |
#render_to_string | Similar to |
#rendered_format | Returns |
#view_assigns | This method should return a hash with assigns. |
#_normalize_args | Normalize args by converting |
#_normalize_options | Normalize options. |
#_process_options | Process extra options. |
::ActionView::ViewPaths
- Included
#any_templates?, | |
#append_view_path | Append a path to the list of view paths for the current LookupContext. |
#details_for_lookup, | |
#lookup_context | LookupContext is the object responsible for holding all information required for looking up templates, i.e. view paths and details. |
#prepend_view_path | Prepend a path to the list of view paths for the current LookupContext. |
#template_exists? |
Metal
- Inherited
#controller_name | Delegates to the class’s |
#reset_session, | |
#url_for | Basic |
::AbstractController::Base
- Inherited
#action_methods | Delegates to the class’s |
#available_action? | Returns true if a method for the action is available and can be dispatched, false otherwise. |
#controller_path | Delegates to the class’s |
#process | Calls the action going through the entire Action Dispatch stack. |
::ActiveSupport::Configurable
- Included
#config | Reads and writes attributes from a configuration OrderedOptions. |
Constructor Details
This class inherits a constructor from ActionController::Metal
Class Method Details
.without_modules(*modules)
Shortcut helper that returns all the API
modules except the ones passed as arguments:
class MyAPIBaseController < ActionController::Metal
ActionController::API.without_modules(:UrlFor).each do |left|
include left
end
end
This gives better control over what you want to exclude and makes it easier to create an API
controller class, instead of listing the modules required manually.
# File 'actionpack/lib/action_controller/api.rb', line 107
def self.without_modules(*modules) modules = modules.map do |m| m.is_a?(Symbol) ? ActionController.const_get(m) : m end MODULES - modules end