api_app.md 17.5 KB
Newer Older
1
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
2 3 4

Using Rails for API-only Applications
=====================================
S
Santiago Pastorino 已提交
5 6 7

In this guide you will learn:

8 9
* What Rails provides for API-only applications
* How to configure Rails to start without any browser features
10
* How to decide which middleware you will want to include
11
* How to decide which modules to use in your controller
S
Santiago Pastorino 已提交
12

13
--------------------------------------------------------------------------------
S
Santiago Pastorino 已提交
14

15 16
What is an API Application?
---------------------------
S
Santiago Pastorino 已提交
17

18 19
Traditionally, when people said that they used Rails as an "API", they meant
providing a programmatically accessible API alongside their web application.
20
For example, GitHub provides [an API](https://developer.github.com) that you
21
can use from your own custom clients.
S
Santiago Pastorino 已提交
22

23 24 25
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.
S
Santiago Pastorino 已提交
26

27
For example, Twitter uses its [public API](https://developer.twitter.com/) in its web
28
application, which is built as a static site that consumes JSON resources.
S
Santiago Pastorino 已提交
29

30 31 32
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.
S
Santiago Pastorino 已提交
33

34
This guide covers building a Rails application that serves JSON resources to an
35
API client, including client-side frameworks.
S
Santiago Pastorino 已提交
36

37
Why Use Rails for JSON APIs?
38
----------------------------
S
Santiago Pastorino 已提交
39

40 41 42
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?".
S
Santiago Pastorino 已提交
43 44

For very simple APIs, this may be true. However, even in very HTML-heavy
J
Jon Moss 已提交
45
applications, most of an application's logic lives outside of the view
46
layer.
S
Santiago Pastorino 已提交
47

48
The reason most people use Rails is that it provides a set of defaults that
J
Jon Moss 已提交
49
allows developers to get up and running quickly, without having to make a lot of trivial
50
decisions.
S
Santiago Pastorino 已提交
51

52 53
Let's take a look at some of the things that Rails provides out of the box that are
still applicable to API applications.
S
Santiago Pastorino 已提交
54 55 56

Handled at the middleware layer:

57 58 59 60 61 62 63 64 65 66 67
- 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
68
  attacks](https://en.wikipedia.org/wiki/IP_address_spoofing) and handles
69
  cryptographic signatures in a [timing
70
  attack](https://en.wikipedia.org/wiki/Timing_attack) aware way. Don't know what
71 72 73 74 75
  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.
76
- Conditional GETs: Rails handles conditional `GET` (`ETag` and `Last-Modified`)
77 78
  processing request headers and returning the correct response headers and status
  code. All you need to do is use the
79
  [`stale?`](https://api.rubyonrails.org/classes/ActionController/ConditionalGet.html#method-i-stale-3F)
80 81 82 83 84
  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.

85
While you could obviously build these up in terms of existing Rack middleware,
86 87 88 89 90 91 92 93 94 95
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
96
  on HTTP includes URLs (see [the GitHub Gist API](https://developer.github.com/v3/gists/)
97 98 99 100
  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?
A
Anthony Crumley 已提交
101
- Caching: Rails provides page, action, and fragment caching. Fragment caching
102
  is especially helpful when building up a nested JSON object.
103
- Basic, Digest, and Token Authentication: Rails comes with out-of-the-box support
104
  for three kinds of HTTP authentication.
105
- Instrumentation: Rails has an instrumentation API that triggers registered
106 107 108
  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
A
Anthony Crumley 已提交
109
  the controller, action, parameters, request format, request method, and the
110
  request's full path).
111 112 113
- 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.
114 115 116
- 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
117
  Rake tasks, and honoring Rails choices (like the logger and cache back-end).
118 119 120 121 122 123 124

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
J
Jon Moss 已提交
125
to be most of it.
126 127 128 129 130 131 132

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.
S
Santiago Pastorino 已提交
133

134 135
### Creating a new application

S
Santiago Pastorino 已提交
136 137
You can generate a new api Rails app:

138 139 140
```bash
$ rails new my_api --api
```
S
Santiago Pastorino 已提交
141 142 143

This will do three main things for you:

144
- Configure your application to start with a more limited set of middleware
145 146 147
  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
148
  `ActionController::Base`. As with middleware, this will leave out any Action
149 150
  Controller modules that provide functionalities primarily used by browser
  applications.
A
Anthony Crumley 已提交
151
- Configure the generators to skip generating views, helpers, and assets when
152 153
  you generate a new resource.

154 155
### Changing an existing application

156
If you want to take an existing application and make it an API one, read the
S
Santiago Pastorino 已提交
157 158
following steps.

159 160 161 162 163 164 165
In `config/application.rb` add the following line at the top of the `Application`
class definition:

```ruby
config.api_only = true
```

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
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
```

181
By default, `config.debug_exception_response_format` is set to `:api`, when `config.api_only` is set to true.
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196
Finally, inside `app/controllers/application_controller.rb`, instead of:

```ruby
class ApplicationController < ActionController::Base
end
```

do:

```ruby
class ApplicationController < ActionController::API
end
```

197
Choosing Middleware
198 199
--------------------

200
An API application comes with the following middleware by default:
201 202 203

- `Rack::Sendfile`
- `ActionDispatch::Static`
204
- `ActionDispatch::Executor`
205
- `ActiveSupport::Cache::Strategy::LocalCache::Middleware`
J
Jon Moss 已提交
206
- `Rack::Runtime`
207
- `ActionDispatch::RequestId`
208
- `ActionDispatch::RemoteIp`
209 210 211 212 213
- `Rails::Rack::Logger`
- `ActionDispatch::ShowExceptions`
- `ActionDispatch::DebugExceptions`
- `ActionDispatch::Reloader`
- `ActionDispatch::Callbacks`
214
- `ActiveRecord::Migration::CheckPending`
215 216 217 218
- `Rack::Head`
- `Rack::ConditionalGet`
- `Rack::ETag`

219
See the [internal middleware](rails_on_rack.html#internal-middleware-stack)
220 221
section of the Rack guide for further information on them.

222 223
Other plugins, including Active Record, may add additional middleware. In
general, these middleware are agnostic to the type of application you are
S
Santiago Pastorino 已提交
224 225
building, and make sense in an API-only Rails application.

226
You can get a list of all middleware in your application via:
S
Santiago Pastorino 已提交
227

228
```bash
229
$ bin/rails middleware
230
```
S
Santiago Pastorino 已提交
231

232
### Using the Cache Middleware
S
Santiago Pastorino 已提交
233

234 235 236
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.
S
Santiago Pastorino 已提交
237

238
For instance, using the `stale?` method:
S
Santiago Pastorino 已提交
239

240 241
```ruby
def show
242
  @post = Post.find(params[:id])
S
Santiago Pastorino 已提交
243

244 245 246 247 248
  if stale?(last_modified: @post.updated_at)
    render json: @post
  end
end
```
S
Santiago Pastorino 已提交
249

250 251 252 253
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.
S
Santiago Pastorino 已提交
254

255
Normally, this mechanism is used on a per-client basis. The cache middleware
S
Santiago Pastorino 已提交
256
allows us to share this caching mechanism across clients. We can enable
257
cross-client caching in the call to `stale?`:
S
Santiago Pastorino 已提交
258

259 260
```ruby
def show
261
  @post = Post.find(params[:id])
S
Santiago Pastorino 已提交
262

263 264 265 266 267
  if stale?(last_modified: @post.updated_at, public: true)
    render json: @post
  end
end
```
S
Santiago Pastorino 已提交
268

269 270
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
S
Santiago Pastorino 已提交
271 272 273 274
subsequent inbound requests for the same URL.

Think of it as page caching using HTTP semantics.

275
### Using Rack::Sendfile
S
Santiago Pastorino 已提交
276

277 278 279
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.
S
Santiago Pastorino 已提交
280

281 282
If your front-end server supports accelerated file sending, `Rack::Sendfile`
will offload the actual file sending work to the front-end server.
S
Santiago Pastorino 已提交
283

284 285 286
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.
S
Santiago Pastorino 已提交
287

288
You can learn more about how to use `Rack::Sendfile` with popular
S
Santiago Pastorino 已提交
289
front-ends in [the Rack::Sendfile
290
documentation](https://www.rubydoc.info/github/rack/rack/master/Rack/Sendfile).
S
Santiago Pastorino 已提交
291

292
Here are some values for this header for some popular servers, once these servers are configured to support
S
Santiago Pastorino 已提交
293 294
accelerated file sending:

295 296 297 298 299 300 301 302 303 304 305
```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.

306
### Using ActionDispatch::Request
307

308
`ActionDispatch::Request#params` will take parameters from the client in the JSON
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
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:

```javascript
jQuery.ajax({
  type: 'POST',
  url: '/people',
  dataType: 'json',
  contentType: 'application/json',
  data: JSON.stringify({ person: { firstName: "Yehuda", lastName: "Katz" } }),
  success: function(json) { }
});
```

327
`ActionDispatch::Request` will see the `Content-Type` and your parameters
328 329 330 331 332 333
will be:

```ruby
{ :person => { :firstName => "Yehuda", :lastName => "Katz" } }
```

334
### Using Session Middlewares
335

336
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:
337

338 339 340 341 342 343
- `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
344 345
`use ActionDispatch::Session::CookieStore` and have sessions functioning as usual.  (To be clear: sessions
may work, but your session options will be ignored - i.e the session key will default to `_session_id`)
346

347
Instead of the initializer, you'll have to set the relevant options somewhere before your middleware is
348
built (like `config/application.rb`) and pass them to your prefered middleware, like this:
349 350

```ruby
351 352 353
config.session_store :cookie_store, key: '_interslice_session' # <-- this also configures session_options for use below
config.middleware.use ActionDispatch::Cookies # Required for all session management (regardless of session_store)
config.middleware.use config.session_store, config.session_options
354 355
```

J
Jon Moss 已提交
356
### Other Middleware
357

358
Rails ships with a number of other middleware that you might want to use in an
359 360 361 362 363 364
API application, especially if one of your API clients is the browser:

- `Rack::MethodOverride`
- `ActionDispatch::Cookies`
- `ActionDispatch::Flash`

365
Any of these middleware can be added via:
366 367 368 369 370

```ruby
config.middleware.use Rack::MethodOverride
```

371
### Removing Middleware
372 373 374 375 376 377 378 379

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
```

380
Keep in mind that removing these middlewares will remove support for certain
381 382 383 384 385 386 387 388
features in Action Controller.

Choosing Controller Modules
---------------------------

An API application (using `ActionController::API`) comes with the following
controller modules by default:

J
Jon Moss 已提交
389
- `ActionController::UrlFor`: Makes `url_for` and similar helpers available.
390
- `ActionController::Redirecting`: Support for `redirect_to`.
J
Jon Moss 已提交
391
- `AbstractController::Rendering` and `ActionController::ApiRendering`: Basic support for rendering.
392 393
- `ActionController::Renderers::All`: Support for `render :json` and friends.
- `ActionController::ConditionalGet`: Support for `stale?`.
394
- `ActionController::BasicImplicitRender`: Makes sure to return an empty response, if there isn't an explicit one.
395
- `ActionController::StrongParameters`: Support for parameters filtering in combination with Active Model mass assignment.
J
Jon Moss 已提交
396 397 398 399 400 401 402 403
- `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).
404
- `ActionController::ParamsWrapper`: Wraps the parameters hash into a nested hash,
405
  so that you don't have to specify root elements sending POST requests for instance.
406
- `ActionController::Head`: Support for returning a response with no content, only headers
407 408 409 410 411

Other plugins may add additional modules. You can get a list of all modules
included into `ActionController::API` in the rails console:

```bash
412
$ bin/rails c
413
>> ActionController::API.ancestors - ActionController::Metal.ancestors
414 415 416 417 418 419
=> [ActionController::API,
    ActiveRecord::Railties::ControllerRuntime,
    ActionDispatch::Routing::RouteSet::MountedHelpers,
    ActionController::ParamsWrapper,
    ... ,
    AbstractController::Rendering,
420
    ActionView::ViewPaths]
421 422 423 424 425 426 427
```

### 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.
S
Santiago Pastorino 已提交
428 429 430

Some common modules you might want to add:

431 432
- `AbstractController::Translation`: Support for the `l` and `t` localization
  and translation methods.
A
Anthony Crumley 已提交
433
- Support for basic, digest, or token HTTP authentication:
434 435 436
  * `ActionController::HttpAuthentication::Basic::ControllerMethods`,
  * `ActionController::HttpAuthentication::Digest::ControllerMethods`,
  * `ActionController::HttpAuthentication::Token::ControllerMethods`
437
- `ActionView::Layouts`: Support for layouts when rendering.
438 439 440
- `ActionController::MimeResponds`: Support for `respond_to`.
- `ActionController::Cookies`: Support for `cookies`, which includes
  support for signed and encrypted cookies. This requires the cookies middleware.
441 442 443 444 445
- `ActionController::Caching`: Support view caching for the API controller. Please notice that
  you will need to manually specify cache store inside the controller like:
  ```ruby
  class ApplicationController < ActionController::API
    include ::ActionController::Caching
446
    self.cache_store = :mem_cache_store
447 448 449
  end
  ```
  Rails does *not* pass this configuration automatically.
450

J
Jon Moss 已提交
451
The best place to add a module is in your `ApplicationController`, but you can
452
also add modules to individual controllers.