Rails::API is a subset of a normal Rails application, created for applications that don't require all functionality that a complete Rails application provides. It is a bit more lightweight, and consequently a bit faster than a normal Rails application. The main example for its usage is in API applications only, where you usually don't need the entire Rails middleware stack nor template generation.
This is a quick walk-through to help you get up and running with Rails::API to create API-only Apps, covering:
- What Rails::API provides for API-only applications
- How to decide which middlewares you will want to include
- How to decide which modules to use in your controller
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 backend 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 dynamic HTML that will communicate with the server through forms and links, many developers are treating their web application as just another client, consuming a simple JSON API.
This guide covers building a Rails application that serves JSON resources to an API client or client-side framework.
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 is actually outside of the view layer.
The reason most people use Rails is that it provides a set of defaults that allows us 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.
- 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 application come with smart defaults for development, making development pleasant without compromising production-time performance.
- Test Mode: Ditto test 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 perform