-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_app.html
646 lines (614 loc) · 38.3 KB
/
api_app.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Using Rails for API-only Applications — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" data-turbolinks-track="reload">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="javascripts/syntaxhighlighter.js" data-turbolinks-track="reload"></script>
<script src="javascripts/turbolinks.js" data-turbolinks-track="reload"></script>
<script src="javascripts/guides.js" data-turbolinks-track="reload"></script>
<script src="javascripts/responsive-tables.js" data-turbolinks-track="reload"></script>
<meta property="og:title" content="Using Rails for API-only Applications — Ruby on Rails Guides" />
<meta name="description" content="Using Rails for API-only ApplicationsIn this guide you will learn: What Rails provides for API-only applications How to configure Rails to start without any browser features How to decide which middleware you will want to include How to decide which modules to use in your controller" />
<meta property="og:description" content="Using Rails for API-only ApplicationsIn this guide you will learn: What Rails provides for API-only applications How to configure Rails to start without any browser features How to decide which middleware you will want to include How to decide which modules to use in your controller" />
<meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="Ruby on Rails Guides" />
<meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" />
<meta property="og:type" content="website" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">공식 웹사이트 <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
루비온레일스 웹사이트
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">블로그</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">영문가이드</a></li>
<li class="more-info"><a href="https://api.rubyonrails.org/">레일스API</a></li>
<li class="more-info"><a href="https://stackoverflow.com/questions/tagged/ruby-on-rails">질문하기</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">GitHub에서 기여하기</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">홈</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">가이드 인덱스</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<div class="guides-section-container">
<div class="guides-section">
<dt>시작하면서</dt>
<dd><a href="getting_started.html">레일스로 시작하기</a></dd>
</div>
<div class="guides-section">
<dt>모델</dt>
<dd><a href="active_record_basics.html">액티브 레코드 기본</a></dd>
<dd><a href="active_record_migrations.html">액티브 레코드 마이그레이션</a></dd>
<dd><a href="active_record_validations.html">액티브 레코드 유효성 검증</a></dd>
<dd><a href="active_record_callbacks.html">액티브 레코드 콜백</a></dd>
<dd><a href="association_basics.html">Active Record Associations</a></dd>
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
</div>
<div class="guides-section">
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
</div>
<div class="guides-section">
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
</div>
<div class="guides-section">
<dt>Other Components</dt>
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
<dd><a href="active_job_basics.html">Active Job Basics</a></dd>
<dd><a href="active_storage_overview.html">Active Storage Overview</a></dd>
<dd><a href="action_cable_overview.html">Action Cable Overview</a></dd>
</div>
<div class="guides-section">
<dt>Digging Deeper</dt>
<dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd>
<dd><a href="testing.html">Testing Rails Applications</a></dd>
<dd><a href="security.html">Securing Rails Applications</a></dd>
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
<dd><a href="command_line.html">The Rails Command Line</a></dd>
<dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
<dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</a></dd>
<dd><a href="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</a></dd>
<dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd>
<dd><a href="api_app.html">Using Rails for API-only Applications</a></dd>
</div>
<div class="guides-section">
<dt>Extending Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd>
</div>
<div class="guides-section">
<dt>Contributions</dt>
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd>
</div>
<div class="guides-section">
<dt>Policies</dt>
<dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
</div>
<div class="guides-section">
<dt>Release Notes</dt>
<dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
<dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd>
<dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd>
<dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd>
<dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd>
<dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd>
<dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd>
<dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd>
<dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd>
<dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd>
<dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd>
<dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd>
<dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd>
</div>
</div>
</div>
</li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">기여하기</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">가이드 인덱스</option>
<optgroup label="시작하면서">
<option value="getting_started.html">레일스로 시작하기</option>
</optgroup>
<optgroup label="모델">
<option value="active_record_basics.html">액티브 레코드 기본</option>
<option value="active_record_migrations.html">액티브 레코드 마이그레이션</option>
<option value="active_record_validations.html">액티브 레코드 유효성 검증</option>
<option value="active_record_callbacks.html">액티브 레코드 콜백</option>
<option value="association_basics.html">Active Record Associations</option>
<option value="active_record_querying.html">Active Record Query Interface</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
<option value="form_helpers.html">Action View Form Helpers</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller Overview</option>
<option value="routing.html">Rails Routing from the Outside In</option>
</optgroup>
<optgroup label="Other Components">
<option value="active_support_core_extensions.html">Active Support Core Extensions</option>
<option value="action_mailer_basics.html">Action Mailer Basics</option>
<option value="active_job_basics.html">Active Job Basics</option>
<option value="active_storage_overview.html">Active Storage Overview</option>
<option value="action_cable_overview.html">Action Cable Overview</option>
</optgroup>
<optgroup label="Digging Deeper">
<option value="i18n.html">Rails Internationalization (I18n) API</option>
<option value="testing.html">Testing Rails Applications</option>
<option value="security.html">Securing Rails Applications</option>
<option value="debugging_rails_applications.html">Debugging Rails Applications</option>
<option value="configuring.html">Configuring Rails Applications</option>
<option value="command_line.html">The Rails Command Line</option>
<option value="asset_pipeline.html">The Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
<option value="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</option>
<option value="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</option>
<option value="caching_with_rails.html">Caching with Rails: An Overview</option>
<option value="api_app.html">Using Rails for API-only Applications</option>
</optgroup>
<optgroup label="Extending Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">Creating and Customizing Rails Generators & Templates</option>
</optgroup>
<optgroup label="Contributions">
<option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
<option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option>
</optgroup>
<optgroup label="Policies">
<option value="maintenance_policy.html">Maintenance Policy</option>
</optgroup>
<optgroup label="Release Notes">
<option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
<option value="6_0_release_notes.html">Version 6.0 - August 2019</option>
<option value="5_2_release_notes.html">Version 5.2 - April 2018</option>
<option value="5_1_release_notes.html">Version 5.1 - April 2017</option>
<option value="5_0_release_notes.html">Version 5.0 - June 2016</option>
<option value="4_2_release_notes.html">Version 4.2 - December 2014</option>
<option value="4_1_release_notes.html">Version 4.1 - April 2014</option>
<option value="4_0_release_notes.html">Version 4.0 - June 2013</option>
<option value="3_2_release_notes.html">Version 3.2 - January 2012</option>
<option value="3_1_release_notes.html">Version 3.1 - August 2011</option>
<option value="3_0_release_notes.html">Version 3.0 - August 2010</option>
<option value="2_3_release_notes.html">Version 2.3 - March 2009</option>
<option value="2_2_release_notes.html">Version 2.2 - November 2008</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Using Rails for API-only Applications</h2><p>In this guide you will learn:</p>
<ul>
<li>What Rails provides for API-only applications</li>
<li>How to configure Rails to start without any browser features</li>
<li>How to decide which middleware you will want to include</li>
<li>How to decide which modules to use in your controller</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#what-is-an-api-application-questionmark">What is an API Application?</a></li>
<li><a href="#why-use-rails-for-json-apis-questionmark">Why Use Rails for JSON APIs?</a></li>
<li>
<a href="#the-basic-configuration">The Basic Configuration</a>
<ul>
<li><a href="#creating-a-new-application">Creating a new application</a></li>
<li><a href="#changing-an-existing-application">Changing an existing application</a></li>
</ul>
</li>
<li>
<a href="#choosing-middleware">Choosing Middleware</a>
<ul>
<li><a href="#using-the-cache-middleware">Using the Cache Middleware</a></li>
<li><a href="#using-rack-sendfile">Using Rack::Sendfile</a></li>
<li><a href="#using-actiondispatch-request">Using ActionDispatch::Request</a></li>
<li><a href="#other-middleware">Other Middleware</a></li>
<li><a href="#removing-middleware">Removing Middleware</a></li>
</ul>
</li>
<li>
<a href="#choosing-controller-modules">Choosing Controller Modules</a>
<ul>
<li><a href="#adding-other-modules">Adding Other Modules</a></li>
</ul>
</li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="what-is-an-api-application-questionmark"><a class="anchorlink" href="#what-is-an-api-application-questionmark">1 What is an API Application?</a></h3><p>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 <a href="https://developer.github.com">an API</a> that you
can use from your own custom clients.</p><p>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.</p><p>For example, Twitter uses its <a href="https://developer.twitter.com/">public API</a> in its web
application, which is built as a static site that consumes JSON resources.</p><p>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.</p><p>This guide covers building a Rails application that serves JSON resources to an
API client, including client-side frameworks.</p><h3 id="why-use-rails-for-json-apis-questionmark"><a class="anchorlink" href="#why-use-rails-for-json-apis-questionmark">2 Why Use Rails for JSON APIs?</a></h3><p>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?".</p><p>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.</p><p>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.</p><p>Let's take a look at some of the things that Rails provides out of the box that are
still applicable to API applications.</p><p>Handled at the middleware layer:</p>
<ul>
<li>Reloading: Rails applications support transparent reloading. This works even if
your application gets big and restarting the server for every request becomes
non-viable.</li>
<li>Development Mode: Rails applications come with smart defaults for development,
making development pleasant without compromising production-time performance.</li>
<li>Test Mode: Ditto development mode.</li>
<li>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.</li>
<li>Security: Rails detects and thwarts <a href="https://en.wikipedia.org/wiki/IP_address_spoofing">IP spoofing
attacks</a> and handles
cryptographic signatures in a <a href="https://en.wikipedia.org/wiki/Timing_attack">timing
attack</a> aware way. Don't know what
an IP spoofing attack or a timing attack is? Exactly.</li>
<li>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 <code>params</code>. Want to use nested URL-encoded parameters? That
works too.</li>
<li>Conditional GETs: Rails handles conditional <code>GET</code> (<code>ETag</code> and <code>Last-Modified</code>)
processing request headers and returning the correct response headers and status
code. All you need to do is use the
<a href="https://api.rubyonrails.org/6-0-stable/classes/ActionController/ConditionalGet.html#method-i-stale-3F"><code>stale?</code></a>
check in your controller, and Rails will handle all of the HTTP details for you.</li>
<li>HEAD requests: Rails will transparently convert <code>HEAD</code> requests into <code>GET</code> ones,
and return just the headers on the way out. This makes <code>HEAD</code> work reliably in
all Rails APIs.</li>
</ul>
<p>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".</p><p>Handled at the Action Pack layer:</p>
<ul>
<li>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.</li>
<li>URL Generation: The flip side of routing is URL generation. A good API based
on HTTP includes URLs (see <a href="https://developer.github.com/v3/gists/">the GitHub Gist API</a>
for an example).</li>
<li>Header and Redirection Responses: <code>head :no_content</code> and
<code>redirect_to user_url(current_user)</code> come in handy. Sure, you could manually
add the response headers, but why?</li>
<li>Caching: Rails provides page, action, and fragment caching. Fragment caching
is especially helpful when building up a nested JSON object.</li>
<li>Basic, Digest, and Token Authentication: Rails comes with out-of-the-box support
for three kinds of HTTP authentication.</li>
<li>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).</li>
<li>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.</li>
<li>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).</li>
</ul>
<p>Of course, the Rails boot process also glues together all registered components.
For example, the Rails boot process is what uses your <code>config/database.yml</code> file
when configuring Active Record.</p><p><strong>The short version is</strong>: 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.</p><h3 id="the-basic-configuration"><a class="anchorlink" href="#the-basic-configuration">3 The Basic Configuration</a></h3><p>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.</p><h4 id="creating-a-new-application"><a class="anchorlink" href="#creating-a-new-application">3.1 Creating a new application</a></h4><p>You can generate a new api Rails app:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails new my_api --api
</pre>
</div>
<p>This will do three main things for you:</p>
<ul>
<li>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.</li>
<li>Make <code>ApplicationController</code> inherit from <code>ActionController::API</code> instead of
<code>ActionController::Base</code>. As with middleware, this will leave out any Action
Controller modules that provide functionalities primarily used by browser
applications.</li>
<li>Configure the generators to skip generating views, helpers, and assets when
you generate a new resource.</li>
</ul>
<h4 id="changing-an-existing-application"><a class="anchorlink" href="#changing-an-existing-application">3.2 Changing an existing application</a></h4><p>If you want to take an existing application and make it an API one, read the
following steps.</p><p>In <code>config/application.rb</code> add the following line at the top of the <code>Application</code>
class definition:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.api_only = true
</pre>
</div>
<p>In <code>config/environments/development.rb</code>, set <code>config.debug_exception_response_format</code>
to configure the format used in responses when errors occur in development mode.</p><p>To render an HTML page with debugging information, use the value <code>:default</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.debug_exception_response_format = :default
</pre>
</div>
<p>To render debugging information preserving the response format, use the value <code>:api</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.debug_exception_response_format = :api
</pre>
</div>
<p>By default, <code>config.debug_exception_response_format</code> is set to <code>:api</code>, when <code>config.api_only</code> is set to true.</p><p>Finally, inside <code>app/controllers/application_controller.rb</code>, instead of:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationController < ActionController::Base
end
</pre>
</div>
<p>do:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationController < ActionController::API
end
</pre>
</div>
<h3 id="choosing-middleware"><a class="anchorlink" href="#choosing-middleware">4 Choosing Middleware</a></h3><p>An API application comes with the following middleware by default:</p>
<ul>
<li><code>Rack::Sendfile</code></li>
<li><code>ActionDispatch::Static</code></li>
<li><code>ActionDispatch::Executor</code></li>
<li><code>ActiveSupport::Cache::Strategy::LocalCache::Middleware</code></li>
<li><code>Rack::Runtime</code></li>
<li><code>ActionDispatch::RequestId</code></li>
<li><code>ActionDispatch::RemoteIp</code></li>
<li><code>Rails::Rack::Logger</code></li>
<li><code>ActionDispatch::ShowExceptions</code></li>
<li><code>ActionDispatch::DebugExceptions</code></li>
<li><code>ActionDispatch::Reloader</code></li>
<li><code>ActionDispatch::Callbacks</code></li>
<li><code>ActiveRecord::Migration::CheckPending</code></li>
<li><code>Rack::Head</code></li>
<li><code>Rack::ConditionalGet</code></li>
<li><code>Rack::ETag</code></li>
</ul>
<p>See the <a href="rails_on_rack.html#internal-middleware-stack">internal middleware</a>
section of the Rack guide for further information on them.</p><p>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.</p><p>You can get a list of all middleware in your application via:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails middleware
</pre>
</div>
<h4 id="using-the-cache-middleware"><a class="anchorlink" href="#using-the-cache-middleware">4.1 Using the Cache Middleware</a></h4><p>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.</p><p>For instance, using the <code>stale?</code> method:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def show
@post = Post.find(params[:id])
if stale?(last_modified: @post.updated_at)
render json: @post
end
end
</pre>
</div>
<p>The call to <code>stale?</code> will compare the <code>If-Modified-Since</code> header in the request
with <code>@post.updated_at</code>. 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 <code>Last-Modified</code> header in it.</p><p>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 <code>stale?</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def show
@post = Post.find(params[:id])
if stale?(last_modified: @post.updated_at, public: true)
render json: @post
end
end
</pre>
</div>
<p>This means that the cache middleware will store off the <code>Last-Modified</code> value
for a URL in the Rails cache, and add an <code>If-Modified-Since</code> header to any
subsequent inbound requests for the same URL.</p><p>Think of it as page caching using HTTP semantics.</p><h4 id="using-rack-sendfile"><a class="anchorlink" href="#using-rack-sendfile">4.2 Using Rack::Sendfile</a></h4><p>When you use the <code>send_file</code> method inside a Rails controller, it sets the
<code>X-Sendfile</code> header. <code>Rack::Sendfile</code> is responsible for actually sending the
file.</p><p>If your front-end server supports accelerated file sending, <code>Rack::Sendfile</code>
will offload the actual file sending work to the front-end server.</p><p>You can configure the name of the header that your front-end server uses for
this purpose using <code>config.action_dispatch.x_sendfile_header</code> in the appropriate
environment's configuration file.</p><p>You can learn more about how to use <code>Rack::Sendfile</code> with popular
front-ends in <a href="https://www.rubydoc.info/github/rack/rack/master/Rack/Sendfile">the Rack::Sendfile
documentation</a>.</p><p>Here are some values for this header for some popular servers, once these servers are configured to support
accelerated file sending:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Apache and lighttpd
config.action_dispatch.x_sendfile_header = "X-Sendfile"
# Nginx
config.action_dispatch.x_sendfile_header = "X-Accel-Redirect"
</pre>
</div>
<p>Make sure to configure your server to support these options following the
instructions in the <code>Rack::Sendfile</code> documentation.</p><h4 id="using-actiondispatch-request"><a class="anchorlink" href="#using-actiondispatch-request">4.3 Using ActionDispatch::Request</a></h4><p><code>ActionDispatch::Request#params</code> will take parameters from the client in the JSON
format and make them available in your controller inside <code>params</code>.</p><p>To use this, your client will need to make a request with JSON-encoded parameters
and specify the <code>Content-Type</code> as <code>application/json</code>.</p><p>Here's an example in jQuery:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
jQuery.ajax({
type: 'POST',
url: '/people',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ person: { firstName: "Yehuda", lastName: "Katz" } }),
success: function(json) { }
});
</pre>
</div>
<p><code>ActionDispatch::Request</code> will see the <code>Content-Type</code> and your parameters
will be:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{ :person => { :firstName => "Yehuda", :lastName => "Katz" } }
</pre>
</div>
<h4 id="other-middleware"><a class="anchorlink" href="#other-middleware">4.4 Other Middleware</a></h4><p>Rails ships with a number of other middleware that you might want to use in an
API application, especially if one of your API clients is the browser:</p>
<ul>
<li><code>Rack::MethodOverride</code></li>
<li><code>ActionDispatch::Cookies</code></li>
<li><code>ActionDispatch::Flash</code></li>
<li>For session management
<ul>
<li><code>ActionDispatch::Session::CacheStore</code></li>
<li><code>ActionDispatch::Session::CookieStore</code></li>
<li><code>ActionDispatch::Session::MemCacheStore</code></li>
</ul>
</li>
</ul>
<p>Any of these middleware can be added via:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.middleware.use Rack::MethodOverride
</pre>
</div>
<h4 id="removing-middleware"><a class="anchorlink" href="#removing-middleware">4.5 Removing Middleware</a></h4><p>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:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.middleware.delete ::Rack::Sendfile
</pre>
</div>
<p>Keep in mind that removing these middlewares will remove support for certain
features in Action Controller.</p><h3 id="choosing-controller-modules"><a class="anchorlink" href="#choosing-controller-modules">5 Choosing Controller Modules</a></h3><p>An API application (using <code>ActionController::API</code>) comes with the following
controller modules by default:</p>
<ul>
<li>
<code>ActionController::UrlFor</code>: Makes <code>url_for</code> and similar helpers available.</li>
<li>
<code>ActionController::Redirecting</code>: Support for <code>redirect_to</code>.</li>
<li>
<code>AbstractController::Rendering</code> and <code>ActionController::ApiRendering</code>: Basic support for rendering.</li>
<li>
<code>ActionController::Renderers::All</code>: Support for <code>render :json</code> and friends.</li>
<li>
<code>ActionController::ConditionalGet</code>: Support for <code>stale?</code>.</li>
<li>
<code>ActionController::BasicImplicitRender</code>: Makes sure to return an empty response, if there isn't an explicit one.</li>
<li>
<code>ActionController::StrongParameters</code>: Support for parameters filtering in combination with Active Model mass assignment.</li>
<li>
<code>ActionController::DataStreaming</code>: Support for <code>send_file</code> and <code>send_data</code>.</li>
<li>
<code>AbstractController::Callbacks</code>: Support for <code>before_action</code> and
similar helpers.</li>
<li>
<code>ActionController::Rescue</code>: Support for <code>rescue_from</code>.</li>
<li>
<code>ActionController::Instrumentation</code>: Support for the instrumentation
hooks defined by Action Controller (see <a href="active_support_instrumentation.html#action-controller">the instrumentation
guide</a> for
more information regarding this).</li>
<li>
<code>ActionController::ParamsWrapper</code>: Wraps the parameters hash into a nested hash,
so that you don't have to specify root elements sending POST requests for instance.</li>
<li>
<code>ActionController::Head</code>: Support for returning a response with no content, only headers</li>
</ul>
<p>Other plugins may add additional modules. You can get a list of all modules
included into <code>ActionController::API</code> in the rails console:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails c
>> ActionController::API.ancestors - ActionController::Metal.ancestors
=> [ActionController::API,
ActiveRecord::Railties::ControllerRuntime,
ActionDispatch::Routing::RouteSet::MountedHelpers,
ActionController::ParamsWrapper,
... ,
AbstractController::Rendering,
ActionView::ViewPaths]
</pre>
</div>
<h4 id="adding-other-modules"><a class="anchorlink" href="#adding-other-modules">5.1 Adding Other Modules</a></h4><p>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.</p><p>Some common modules you might want to add:</p>
<ul>
<li>
<code>AbstractController::Translation</code>: Support for the <code>l</code> and <code>t</code> localization
and translation methods.</li>
<li>Support for basic, digest, or token HTTP authentication:
<ul>
<li>
<code>ActionController::HttpAuthentication::Basic::ControllerMethods</code>,</li>
<li>
<code>ActionController::HttpAuthentication::Digest::ControllerMethods</code>,</li>
<li><code>ActionController::HttpAuthentication::Token::ControllerMethods</code></li>
</ul>
</li>
<li>
<code>ActionView::Layouts</code>: Support for layouts when rendering.</li>
<li>
<code>ActionController::MimeResponds</code>: Support for <code>respond_to</code>.</li>
<li>
<code>ActionController::Cookies</code>: Support for <code>cookies</code>, which includes
support for signed and encrypted cookies. This requires the cookies middleware.</li>
<li>
<code>ActionController::Caching</code>: Support view caching for the API controller. Please notice that
you will need to manually specify cache store inside the controller like:
<code>ruby
class ApplicationController < ActionController::API
include ::ActionController::Caching
self.cache_store = :mem_cache_store
end
</code>
Rails does <em>not</em> pass this configuration automatically.</li>
</ul>
<p>The best place to add a module is in your <code>ApplicationController</code>, but you can
also add modules to individual controllers.</p>
<h3>피드백</h3>
<p>
이 가이드의 품질을 향상시키기 위해 여러분의 도움이 필요하다.
</p>
<p>
오타나 실제 오류를 발견시 여러분의 기여를 권고한다. 시작하려면 본 <a href="https://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">가이드의 기여</a> 섹션을 읽어보기 바란다.
</p>
<p>
미완성된 컨텐츠나 업데이트되지 않은 내용을 발견할 수도 있다. 누락된 문서는 master 브랜치에 추가한다. 제시된 이슈들이 master 브랜치 상에서 이미 해결되었는지 여부를 확인하려면 먼저 <a href="https://edgeguides.rubyonrails.org">Edge Guides</a>를 확인한다. 스타일과 규칙에 대해서는 <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>을 확인한다.
</p>
<p>
어떤 이유로든 고칠 수 있지만 직접 패치 할 수 없는 경우 <a href="https://github.com/rails/rails/issues">이슈를 새로 오픈</a>하면 된다.
</p>
<p>
그리고 마지막으로, 루비온레일스 문서에 관한 모든 논의는 <a href="https://groups.google.com/forum/#!forum/rubyonrails-docs">rubyonrails-docs 메일링 리스트</a> 상에서 언제든지 가능하다.
</p>
</div>
</div>
</div>
<hr class="hide" />
<div id="footer">
<div class="wrapper">
<p>본 결과물은 <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a> 를 준수한다. </p>
<p>"Rails", "Ruby on Rails", 그리고 레일스 로고는 David Heinemeier Hansson의 등록상표이다. 판권 소유.</p>
</div>
</div>
</body>
</html>