2018-07-23 22:29:31 -04:00
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
2015-06-14 15:03:13 -04:00
Using Rails for API-only Applications
=====================================
2015-05-14 17:30:14 -04:00
In this guide you will learn:
2015-06-14 15:03:13 -04:00
* What Rails provides for API-only applications
* How to configure Rails to start without any browser features
2016-01-28 17:23:11 -05:00
* How to decide which middleware you will want to include
2015-06-14 15:03:13 -04:00
* How to decide which modules to use in your controller
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
--------------------------------------------------------------------------------
2015-05-14 17:30:14 -04:00
2016-02-18 17:29:29 -05:00
What is an API Application?
---------------------------
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
Traditionally, when people said that they used Rails as an "API", they meant
providing a programmatically accessible API alongside their web application.
2017-08-18 19:23:37 -04:00
For example, GitHub provides [an API ](https://developer.github.com ) that you
2015-06-14 15:03:13 -04:00
can use from your own custom clients.
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
With the advent of client-side frameworks, more developers are using Rails to
build a back-end that is shared between their web application and other native
applications.
2015-05-14 17:30:14 -04:00
2018-03-31 06:14:00 -04:00
For example, Twitter uses its [public API ](https://developer.twitter.com/ ) in its web
2015-06-14 15:03:13 -04:00
application, which is built as a static site that consumes JSON resources.
2015-05-14 17:30:14 -04:00
2016-02-18 17:29:29 -05:00
Instead of using Rails to generate HTML that communicates with the server
through forms and links, many developers are treating their web application as
just an API client delivered as HTML with JavaScript that consumes a JSON API.
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
This guide covers building a Rails application that serves JSON resources to an
2016-02-18 17:29:29 -05:00
API client, including client-side frameworks.
2015-05-14 17:30:14 -04:00
2016-02-18 17:29:29 -05:00
Why Use Rails for JSON APIs?
2015-06-14 15:03:13 -04:00
----------------------------
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
The first question a lot of people have when thinking about building a JSON API
using Rails is: "isn't using Rails to spit out some JSON overkill? Shouldn't I
just use something like Sinatra?".
2015-05-14 17:30:14 -04:00
For very simple APIs, this may be true. However, even in very HTML-heavy
2016-01-28 17:56:51 -05:00
applications, most of an application's logic lives outside of the view
2015-06-14 15:03:13 -04:00
layer.
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
The reason most people use Rails is that it provides a set of defaults that
2016-01-28 17:56:51 -05:00
allows developers to get up and running quickly, without having to make a lot of trivial
2015-06-14 15:03:13 -04:00
decisions.
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
Let's take a look at some of the things that Rails provides out of the box that are
still applicable to API applications.
2015-05-14 17:30:14 -04:00
Handled at the middleware layer:
2015-06-14 15:03:13 -04:00
- Reloading: Rails applications support transparent reloading. This works even if
your application gets big and restarting the server for every request becomes
non-viable.
- Development Mode: Rails applications come with smart defaults for development,
making development pleasant without compromising production-time performance.
- Test Mode: Ditto development mode.
- Logging: Rails applications log every request, with a level of verbosity
appropriate for the current mode. Rails logs in development include information
about the request environment, database queries, and basic performance
information.
- Security: Rails detects and thwarts [IP spoofing
2017-08-22 20:36:38 -04:00
attacks](https://en.wikipedia.org/wiki/IP_address_spoofing) and handles
2015-06-14 15:03:13 -04:00
cryptographic signatures in a [timing
2017-08-22 20:36:38 -04:00
attack](https://en.wikipedia.org/wiki/Timing_attack) aware way. Don't know what
2015-06-14 15:03:13 -04:00
an IP spoofing attack or a timing attack is? Exactly.
- Parameter Parsing: Want to specify your parameters as JSON instead of as a
URL-encoded String? No problem. Rails will decode the JSON for you and make
it available in `params` . Want to use nested URL-encoded parameters? That
works too.
2016-02-18 17:29:29 -05:00
- Conditional GETs: Rails handles conditional `GET` (`ETag` and `Last-Modified` )
2015-06-14 15:03:13 -04:00
processing request headers and returning the correct response headers and status
code. All you need to do is use the
2019-03-05 22:00:45 -05:00
[`stale?` ](https://api.rubyonrails.org/classes/ActionController/ConditionalGet.html#method-i-stale-3F )
2015-06-14 15:03:13 -04:00
check in your controller, and Rails will handle all of the HTTP details for you.
- HEAD requests: Rails will transparently convert `HEAD` requests into `GET` ones,
and return just the headers on the way out. This makes `HEAD` work reliably in
all Rails APIs.
2016-01-28 17:23:11 -05:00
While you could obviously build these up in terms of existing Rack middleware,
2015-06-14 15:03:13 -04:00
this list demonstrates that the default Rails middleware stack provides a lot
of value, even if you're "just generating JSON".
Handled at the Action Pack layer:
- Resourceful Routing: If you're building a RESTful JSON API, you want to be
using the Rails router. Clean and conventional mapping from HTTP to controllers
means not having to spend time thinking about how to model your API in terms
of HTTP.
- URL Generation: The flip side of routing is URL generation. A good API based
2020-08-06 11:10:49 -04:00
on HTTP includes URLs (see [the GitHub Gist API ](https://docs.github.com/en/rest/reference/gists )
2015-06-14 15:03:13 -04:00
for an example).
- Header and Redirection Responses: `head :no_content` and
`redirect_to user_url(current_user)` come in handy. Sure, you could manually
add the response headers, but why?
2018-05-08 22:48:07 -04:00
- Caching: Rails provides page, action, and fragment caching. Fragment caching
2015-06-14 15:03:13 -04:00
is especially helpful when building up a nested JSON object.
2016-02-18 17:29:29 -05:00
- Basic, Digest, and Token Authentication: Rails comes with out-of-the-box support
2015-06-14 15:03:13 -04:00
for three kinds of HTTP authentication.
2016-02-18 17:29:29 -05:00
- Instrumentation: Rails has an instrumentation API that triggers registered
2015-06-14 15:03:13 -04:00
handlers for a variety of events, such as action processing, sending a file or
data, redirection, and database queries. The payload of each event comes with
relevant information (for the action processing event, the payload includes
2018-05-08 22:48:07 -04:00
the controller, action, parameters, request format, request method, and the
2015-06-14 15:03:13 -04:00
request's full path).
2016-02-18 17:29:29 -05:00
- Generators: It is often handy to generate a resource and get your model,
controller, test stubs, and routes created for you in a single command for
further tweaking. Same for migrations and others.
2015-06-14 15:03:13 -04:00
- Plugins: Many third-party libraries come with support for Rails that reduce
or eliminate the cost of setting up and gluing together the library and the
web framework. This includes things like overriding default generators, adding
2016-02-18 17:29:29 -05:00
Rake tasks, and honoring Rails choices (like the logger and cache back-end).
2015-06-14 15:03:13 -04:00
Of course, the Rails boot process also glues together all registered components.
For example, the Rails boot process is what uses your `config/database.yml` file
when configuring Active Record.
**The short version is**: you may not have thought about which parts of Rails
are still applicable even if you remove the view layer, but the answer turns out
2016-01-28 17:56:51 -05:00
to be most of it.
2015-06-14 15:03:13 -04:00
The Basic Configuration
-----------------------
If you're building a Rails application that will be an API server first and
foremost, you can start with a more limited subset of Rails and add in features
as needed.
2015-05-14 17:30:14 -04:00
2016-02-07 02:25:03 -05:00
### Creating a new application
2015-05-14 17:30:14 -04:00
You can generate a new api Rails app:
2015-06-14 15:03:13 -04:00
```bash
$ rails new my_api --api
```
2015-05-14 17:30:14 -04:00
This will do three main things for you:
2016-01-28 17:23:11 -05:00
- Configure your application to start with a more limited set of middleware
2015-06-14 15:03:13 -04:00
than normal. Specifically, it will not include any middleware primarily useful
for browser applications (like cookies support) by default.
- Make `ApplicationController` inherit from `ActionController::API` instead of
2016-01-28 17:23:11 -05:00
`ActionController::Base` . As with middleware, this will leave out any Action
2015-06-14 15:03:13 -04:00
Controller modules that provide functionalities primarily used by browser
applications.
2018-05-08 22:48:07 -04:00
- Configure the generators to skip generating views, helpers, and assets when
2015-06-14 15:03:13 -04:00
you generate a new resource.
2016-02-07 02:25:03 -05:00
### Changing an existing application
2015-06-14 15:03:13 -04:00
If you want to take an existing application and make it an API one, read the
2015-05-14 17:30:14 -04:00
following steps.
2015-06-14 15:03:13 -04:00
In `config/application.rb` add the following line at the top of the `Application`
class definition:
```ruby
config.api_only = true
```
2016-02-19 01:22:50 -05:00
In `config/environments/development.rb` , set `config.debug_exception_response_format`
to configure the format used in responses when errors occur in development mode.
To render an HTML page with debugging information, use the value `:default` .
```ruby
config.debug_exception_response_format = :default
```
To render debugging information preserving the response format, use the value `:api` .
```ruby
config.debug_exception_response_format = :api
```
2016-04-23 01:52:43 -04:00
By default, `config.debug_exception_response_format` is set to `:api` , when `config.api_only` is set to true.
2016-02-19 01:22:50 -05:00
2015-06-14 15:03:13 -04:00
Finally, inside `app/controllers/application_controller.rb` , instead of:
```ruby
class ApplicationController < ActionController::Base
end
```
do:
```ruby
class ApplicationController < ActionController::API
end
```
2016-01-28 17:23:11 -05:00
Choosing Middleware
2015-06-14 15:03:13 -04:00
--------------------
2016-01-28 17:23:11 -05:00
An API application comes with the following middleware by default:
2015-06-14 15:03:13 -04:00
2020-01-22 23:49:47 -05:00
- `ActionDispatch::HostAuthorization`
2015-06-14 15:03:13 -04:00
- `Rack::Sendfile`
- `ActionDispatch::Static`
2016-04-30 22:23:28 -04:00
- `ActionDispatch::Executor`
2015-06-14 15:03:13 -04:00
- `ActiveSupport::Cache::Strategy::LocalCache::Middleware`
- `ActionDispatch::RequestId`
2017-05-21 10:19:05 -04:00
- `ActionDispatch::RemoteIp`
2015-06-14 15:03:13 -04:00
- `Rails::Rack::Logger`
- `ActionDispatch::ShowExceptions`
- `ActionDispatch::DebugExceptions`
2020-01-22 23:49:47 -05:00
- `ActionDispatch::ActionableExceptions`
2015-06-14 15:03:13 -04:00
- `ActionDispatch::Reloader`
- `ActionDispatch::Callbacks`
2016-05-15 16:08:16 -04:00
- `ActiveRecord::Migration::CheckPending`
2015-06-14 15:03:13 -04:00
- `Rack::Head`
- `Rack::ConditionalGet`
- `Rack::ETag`
2016-01-28 17:23:11 -05:00
See the [internal middleware ](rails_on_rack.html#internal-middleware-stack )
2015-06-14 15:03:13 -04:00
section of the Rack guide for further information on them.
2016-01-28 17:23:11 -05:00
Other plugins, including Active Record, may add additional middleware. In
general, these middleware are agnostic to the type of application you are
2015-05-14 17:30:14 -04:00
building, and make sense in an API-only Rails application.
2016-01-28 17:23:11 -05:00
You can get a list of all middleware in your application via:
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
```bash
2019-01-22 03:53:47 -05:00
$ bin/rails middleware
2015-06-14 15:03:13 -04:00
```
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
### Using the Cache Middleware
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
By default, Rails will add a middleware that provides a cache store based on
the configuration of your application (memcache by default). This means that
the built-in HTTP cache will rely on it.
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
For instance, using the `stale?` method:
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
```ruby
def show
2015-11-18 22:14:13 -05:00
@post = Post.find(params[:id])
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
if stale?(last_modified: @post .updated_at)
render json: @post
end
end
```
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
The call to `stale?` will compare the `If-Modified-Since` header in the request
with `@post.updated_at` . If the header is newer than the last modified, this
action will return a "304 Not Modified" response. Otherwise, it will render the
response and include a `Last-Modified` header in it.
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
Normally, this mechanism is used on a per-client basis. The cache middleware
2015-05-14 17:30:14 -04:00
allows us to share this caching mechanism across clients. We can enable
2015-06-14 15:03:13 -04:00
cross-client caching in the call to `stale?` :
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
```ruby
def show
2015-11-18 22:14:13 -05:00
@post = Post.find(params[:id])
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
if stale?(last_modified: @post .updated_at, public: true)
render json: @post
end
end
```
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
This means that the cache middleware will store off the `Last-Modified` value
for a URL in the Rails cache, and add an `If-Modified-Since` header to any
2015-05-14 17:30:14 -04:00
subsequent inbound requests for the same URL.
Think of it as page caching using HTTP semantics.
2015-06-14 15:03:13 -04:00
### Using Rack::Sendfile
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
When you use the `send_file` method inside a Rails controller, it sets the
`X-Sendfile` header. `Rack::Sendfile` is responsible for actually sending the
file.
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
If your front-end server supports accelerated file sending, `Rack::Sendfile`
will offload the actual file sending work to the front-end server.
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
You can configure the name of the header that your front-end server uses for
this purpose using `config.action_dispatch.x_sendfile_header` in the appropriate
environment's configuration file.
2015-05-14 17:30:14 -04:00
2015-06-14 15:03:13 -04:00
You can learn more about how to use `Rack::Sendfile` with popular
2015-05-14 17:30:14 -04:00
front-ends in [the Rack::Sendfile
2019-03-05 22:00:45 -05:00
documentation](https://www.rubydoc.info/github/rack/rack/master/Rack/Sendfile).
2015-05-14 17:30:14 -04:00
2016-05-10 18:31:40 -04:00
Here are some values for this header for some popular servers, once these servers are configured to support
2015-05-14 17:30:14 -04:00
accelerated file sending:
2015-06-14 15:03:13 -04:00
```ruby
# Apache and lighttpd
config.action_dispatch.x_sendfile_header = "X-Sendfile"
# Nginx
config.action_dispatch.x_sendfile_header = "X-Accel-Redirect"
```
Make sure to configure your server to support these options following the
instructions in the `Rack::Sendfile` documentation.
2015-09-18 18:36:55 -04:00
### Using ActionDispatch::Request
2015-06-14 15:03:13 -04:00
2015-09-18 18:36:55 -04:00
`ActionDispatch::Request#params` will take parameters from the client in the JSON
2015-06-14 15:03:13 -04:00
format and make them available in your controller inside `params` .
To use this, your client will need to make a request with JSON-encoded parameters
and specify the `Content-Type` as `application/json` .
Here's an example in jQuery:
2020-07-12 20:28:35 -04:00
```js
2015-06-14 15:03:13 -04:00
jQuery.ajax({
type: 'POST',
url: '/people',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ person: { firstName: "Yehuda", lastName: "Katz" } }),
success: function(json) { }
});
```
2015-09-18 18:36:55 -04:00
`ActionDispatch::Request` will see the `Content-Type` and your parameters
2015-06-14 15:03:13 -04:00
will be:
```ruby
{ :person => { :firstName => "Yehuda", :lastName => "Katz" } }
```
2017-02-14 17:51:14 -05:00
### Using Session Middlewares
2019-12-31 08:01:56 -05:00
2019-12-26 10:25:47 -05:00
The following middlewares, used for session management, are excluded from API apps since they normally don't need sessions. If one of your API clients is a browser, you might want to add one of these back in:
2019-12-31 08:01:56 -05:00
2017-02-14 17:51:14 -05:00
- `ActionDispatch::Session::CacheStore`
- `ActionDispatch::Session::CookieStore`
- `ActionDispatch::Session::MemCacheStore`
The trick to adding these back in is that, by default, they are passed `session_options`
when added (including the session key), so you can't just add a `session_store.rb` initializer, add
2019-12-26 10:25:47 -05:00
`use ActionDispatch::Session::CookieStore` and have sessions functioning as usual. (To be clear: sessions
2021-04-11 13:30:55 -04:00
may work, but your session options will be ignored - i.e. the session key will default to `_session_id` )
2017-02-14 17:51:14 -05:00
2019-12-26 10:25:47 -05:00
Instead of the initializer, you'll have to set the relevant options somewhere before your middleware is
2020-01-04 07:10:41 -05:00
built (like `config/application.rb` ) and pass them to your preferred middleware, like this:
2017-02-14 17:51:14 -05:00
```ruby
2020-08-06 11:10:49 -04:00
# This also configures session_options for use below
config.session_store :cookie_store, key: '_interslice_session'
# Required for all session management (regardless of session_store)
config.middleware.use ActionDispatch::Cookies
2019-12-26 10:25:47 -05:00
config.middleware.use config.session_store, config.session_options
2017-02-14 17:51:14 -05:00
```
2016-01-28 17:56:51 -05:00
### Other Middleware
2015-06-14 15:03:13 -04:00
2016-01-28 17:23:11 -05:00
Rails ships with a number of other middleware that you might want to use in an
2015-06-14 15:03:13 -04:00
API application, especially if one of your API clients is the browser:
- `Rack::MethodOverride`
- `ActionDispatch::Cookies`
- `ActionDispatch::Flash`
2016-01-28 17:23:11 -05:00
Any of these middleware can be added via:
2015-06-14 15:03:13 -04:00
```ruby
config.middleware.use Rack::MethodOverride
```
2016-01-28 17:23:11 -05:00
### Removing Middleware
2015-06-14 15:03:13 -04:00
If you don't want to use a middleware that is included by default in the API-only
middleware set, you can remove it with:
```ruby
config.middleware.delete ::Rack::Sendfile
```
2017-05-21 10:19:05 -04:00
Keep in mind that removing these middlewares will remove support for certain
2015-06-14 15:03:13 -04:00
features in Action Controller.
Choosing Controller Modules
---------------------------
An API application (using `ActionController::API` ) comes with the following
controller modules by default:
2016-01-28 17:56:51 -05:00
- `ActionController::UrlFor` : Makes `url_for` and similar helpers available.
2015-06-14 15:03:13 -04:00
- `ActionController::Redirecting` : Support for `redirect_to` .
2016-01-28 17:56:51 -05:00
- `AbstractController::Rendering` and `ActionController::ApiRendering` : Basic support for rendering.
2015-06-14 15:03:13 -04:00
- `ActionController::Renderers::All` : Support for `render :json` and friends.
- `ActionController::ConditionalGet` : Support for `stale?` .
2016-05-15 17:26:14 -04:00
- `ActionController::BasicImplicitRender` : Makes sure to return an empty response, if there isn't an explicit one.
2019-01-29 11:47:55 -05:00
- `ActionController::StrongParameters` : Support for parameters filtering in combination with Active Model mass assignment.
2016-01-28 17:56:51 -05:00
- `ActionController::DataStreaming` : Support for `send_file` and `send_data` .
- `AbstractController::Callbacks` : Support for `before_action` and
similar helpers.
- `ActionController::Rescue` : Support for `rescue_from` .
- `ActionController::Instrumentation` : Support for the instrumentation
hooks defined by Action Controller (see [the instrumentation
guide](active_support_instrumentation.html#action-controller) for
more information regarding this).
2017-05-21 10:19:05 -04:00
- `ActionController::ParamsWrapper` : Wraps the parameters hash into a nested hash,
2016-05-15 17:26:14 -04:00
so that you don't have to specify root elements sending POST requests for instance.
2020-08-06 11:10:49 -04:00
- `ActionController::Head` : Support for returning a response with no content, only headers.
2015-06-14 15:03:13 -04:00
Other plugins may add additional modules. You can get a list of all modules
included into `ActionController::API` in the rails console:
2020-10-31 17:44:05 -04:00
```irb
irb> ActionController::API.ancestors - ActionController::Metal.ancestors
2017-05-21 10:19:05 -04:00
=> [ActionController::API,
ActiveRecord::Railties::ControllerRuntime,
ActionDispatch::Routing::RouteSet::MountedHelpers,
ActionController::ParamsWrapper,
... ,
AbstractController::Rendering,
2016-05-13 13:59:37 -04:00
ActionView::ViewPaths]
2015-06-14 15:03:13 -04:00
```
### Adding Other Modules
All Action Controller modules know about their dependent modules, so you can feel
free to include any modules into your controllers, and all dependencies will be
included and set up as well.
2015-05-14 17:30:14 -04:00
Some common modules you might want to add:
2015-06-14 15:03:13 -04:00
- `AbstractController::Translation` : Support for the `l` and `t` localization
and translation methods.
2018-05-08 22:48:07 -04:00
- Support for basic, digest, or token HTTP authentication:
2020-08-06 11:10:49 -04:00
* `ActionController::HttpAuthentication::Basic::ControllerMethods`
* `ActionController::HttpAuthentication::Digest::ControllerMethods`
2017-11-19 14:54:30 -05:00
* `ActionController::HttpAuthentication::Token::ControllerMethods`
2016-04-30 21:05:37 -04:00
- `ActionView::Layouts` : Support for layouts when rendering.
2015-06-14 15:03:13 -04:00
- `ActionController::MimeResponds` : Support for `respond_to` .
- `ActionController::Cookies` : Support for `cookies` , which includes
support for signed and encrypted cookies. This requires the cookies middleware.
2020-08-06 11:10:49 -04:00
- `ActionController::Caching` : Support view caching for the API controller. Please note
that you will need to manually specify the cache store inside the controller like this:
```ruby
class ApplicationController < ActionController::API
include ::ActionController::Caching
self.cache_store = :mem_cache_store
end
```
2019-04-22 22:31:37 -04:00
Rails does *not* pass this configuration automatically.
2015-06-14 15:03:13 -04:00
2016-01-28 17:56:51 -05:00
The best place to add a module is in your `ApplicationController` , but you can
2015-06-14 15:03:13 -04:00
also add modules to individual controllers.