Traditionally, when people said that they used Rails as an "API", they meant
providing a programmatically accessible API alongside their web application.
For example, GitHub provides an API that you
can use from your own custom clients.

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.

For example, Twitter uses its public API in its web
application, which is built as a static site that consumes JSON resources.

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.

This guide covers building a Rails application that serves JSON resources to an
API client, including client-side frameworks.

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?".

For very simple APIs, this may be true. However, even in very HTML-heavy
applications, most of an application's logic lives outside of the view
layer.

The reason most people use Rails is that it provides a set of defaults that
allows developers to get up and running quickly, without having to make a lot of trivial
decisions.

Let's take a look at some of the things that Rails provides out of the box that are
still applicable to API applications.

Handled at the middleware layer:

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.

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.

Conditional GETs: Rails handles conditional GET (ETag and Last-Modified)
processing request headers and returning the correct response headers and status
code. All you need to do is use the
stale?
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.

While you could obviously build these up in terms of existing Rack middleware,
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
on HTTP includes URLs (see the GitHub Gist API
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?

Caching: Rails provides page, action, and fragment caching. Fragment caching
is especially helpful when building up a nested JSON object.

Basic, Digest, and Token Authentication: Rails comes with out-of-the-box support
for three kinds of HTTP authentication.

Instrumentation: Rails has an instrumentation API that triggers registered
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
the controller, action, parameters, request format, request method, and the
request's full path).

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.

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
Rake tasks, and honoring Rails choices (like the logger and cache back-end).

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
to be most of it.

Configure your application to start with a more limited set of middleware
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
ActionController::Base. As with middleware, this will leave out any Action
Controller modules that provide functionalities primarily used by browser
applications.

Configure the generators to skip generating views, helpers, and assets when
you generate a new resource.

Other plugins, including Active Record, may add additional middleware. In
general, these middleware are agnostic to the type of application you are
building, and make sense in an API-only Rails application.

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.

For instance, using the stale? method:

def show
@post = Post.find(params[:id])
if stale?(last_modified: @post.updated_at)
render json: @post
end
end

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.

Normally, this mechanism is used on a per-client basis. The cache middleware
allows us to share this caching mechanism across clients. We can enable
cross-client caching in the call to stale?:

Feedback

You may also find incomplete content or stuff that is not up to date.
Please do add any missing documentation for master. Make sure to check
Edge Guides first to verify
if the issues are already fixed or not on the master branch.
Check the Ruby on Rails Guides Guidelines
for style and conventions.

If for whatever reason you spot something to fix but cannot patch it yourself, please
open an issue.