-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrest-api.html
More file actions
945 lines (924 loc) · 53.5 KB
/
rest-api.html
File metadata and controls
945 lines (924 loc) · 53.5 KB
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
<!doctype html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>REST APIs — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbo-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/highlight.css" data-turbo-track="reload">
<link rel="icon" href="images/backend-development.svg" sizes="any">
<script src="javascripts/@hotwired--turbo.js" data-turbo-track="reload"></script>
<script src="javascripts/clipboard.js" data-turbo-track="reload"></script>
<script src="javascripts/guides.js" data-turbo-track="reload"></script>
<meta property="og:title" content="REST APIs — Ruby on Rails Guides" />
<meta name="description" content="REST APIsAfter working through this guide you will: know about the thinking behind REST APIs be able to configure your existing Rails controllers to offer resources as JSON be able to set up an API for your Rails app that is separate from existing controllers You can study the code and try out the demo for the example described here." />
<meta property="og:description" content="REST APIsAfter working through this guide you will: know about the thinking behind REST APIs be able to configure your existing Rails controllers to offer resources as JSON be able to set up an API for your Rails app that is separate from existing controllers You can study the code and try out the demo for the example described here." />
<meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="Textbook Backend Developemnt" />
<meta property="og:image" content="images/backend-development.svg" />
<meta property="og:type" content="website" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Heebo:wght@100..900&family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet">
<meta name="theme-color" content="#2e56e9">
</head>
<body class="guide">
<header id="page_header">
<div class="wrapper clearfix">
<nav id="feature_nav">
<div class="header-logo">
<a href="/">Backend Development</a>
</div>
<ul class="nav">
<li><a class="nav-item" id="home_nav" href="/">Home</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Index</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="guides-section-container">
<div class="guides-section">
<dt>Ruby on Rails</dt>
<dd><a href="ruby_commandline.html">Ruby Commandline</a></dd>
<dd><a href="rails_database_and_model.html">Models and ActiveRecord</a></dd>
<dd><a href="rails_db.html">Database and Migrations</a></dd>
<dd><a href="rails_associations_and_validations.html">Associations and Validations</a></dd>
<dd><a href="rails_view_and_controller.html">Routing, View and Controller</a></dd>
<dd><a href="rails_authentication.html">Simple Authentication</a></dd>
<dd><a href="assets_and_import_map.html">The Asset Pipeline and Importmaps</a></dd>
<dd><a href="testing.html">Getting started with Testing</a></dd>
<dd><a href="refactoring_rails.html">Refactoring Rails</a></dd>
<dd><a href="deploy-to-paas.html">Deploy to PAAS</a></dd>
<dd><a href="rails_gems.html">Ruby Gems for your Rails Project</a></dd>
<dd><a href="deploying_rails.html">Deploying Rails</a></dd>
</div>
<div class="guides-section">
<dt>Ruby on Rails - Advanced Topics</dt>
<dd><a href="deploy-to-paas.html">Deploy to PAAS</a></dd>
<dd><a href="rest-api.html">REST API</a></dd>
<dd><a href="graphql-api.html">GraphQL API</a></dd>
<dd><a href="rails_websockets.html">Websocket in Rails</a></dd>
<dd><a href="jobs_and_tasks.html">Jobs and Tasks in Rails</a></dd>
<dd><a href="rails_security.html">Rails Security</a></dd>
</div>
<div class="guides-section">
<dt>Overarching Concerns</dt>
<dd><a href="issue.html">Issue Lifecycle</a></dd>
<dd><a href="security.html">Security</a></dd>
<dd><a href="adv_authentication.html">Advanced Authentication</a></dd>
<dd><a href="caching.html">Caching</a></dd>
<dd><a href="advanced_testing.html">Advanced Testing</a></dd>
<dd><a href="internationalization.html">Internationalization (I18n)</a></dd>
<dd><a href="git_rebasing.html">Git Rebasing</a></dd>
</div>
<div class="guides-section">
<dt>Nodes.js</dt>
<dd><a href="node_vs_rails.html">Node vs. Rails</a></dd>
<dd><a href="node_basics.html">Node Basics</a></dd>
<dd><a href="node_websockets.html">Node Websockets</a></dd>
<dd><a href="node_express.html">Node Web App</a></dd>
<dd><a href="node_cluster.html">Scaling Node</a></dd>
</div>
<div class="guides-section">
<dt>Next.js</dt>
<dd><a href="nextjs.html">Next.js</a></dd>
</div>
</dl>
</div>
</li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">Index</option>
<optgroup label="Ruby on Rails">
<option value="ruby_commandline.html">Ruby Commandline</option>
<option value="rails_database_and_model.html">Models and ActiveRecord</option>
<option value="rails_db.html">Database and Migrations</option>
<option value="rails_associations_and_validations.html">Associations and Validations</option>
<option value="rails_view_and_controller.html">Routing, View and Controller</option>
<option value="rails_authentication.html">Simple Authentication</option>
<option value="assets_and_import_map.html">The Asset Pipeline and Importmaps</option>
<option value="testing.html">Getting started with Testing</option>
<option value="refactoring_rails.html">Refactoring Rails</option>
<option value="deploy-to-paas.html">Deploy to PAAS</option>
<option value="rails_gems.html">Ruby Gems for your Rails Project</option>
<option value="deploying_rails.html">Deploying Rails</option>
</optgroup>
<optgroup label="Ruby on Rails - Advanced Topics">
<option value="deploy-to-paas.html">Deploy to PAAS</option>
<option value="rest-api.html">REST API</option>
<option value="graphql-api.html">GraphQL API</option>
<option value="rails_websockets.html">Websocket in Rails</option>
<option value="jobs_and_tasks.html">Jobs and Tasks in Rails</option>
<option value="rails_security.html">Rails Security</option>
</optgroup>
<optgroup label="Overarching Concerns">
<option value="issue.html">Issue Lifecycle</option>
<option value="security.html">Security</option>
<option value="adv_authentication.html">Advanced Authentication</option>
<option value="caching.html">Caching</option>
<option value="advanced_testing.html">Advanced Testing</option>
<option value="internationalization.html">Internationalization (I18n)</option>
<option value="git_rebasing.html">Git Rebasing</option>
</optgroup>
<optgroup label="Nodes.js">
<option value="node_vs_rails.html">Node vs. Rails</option>
<option value="node_basics.html">Node Basics</option>
<option value="node_websockets.html">Node Websockets</option>
<option value="node_express.html">Node Web App</option>
<option value="node_cluster.html">Scaling Node</option>
</optgroup>
<optgroup label="Next.js">
<option value="nextjs.html">Next.js</option>
</optgroup>
</select>
</li>
</ul>
</nav>
</div>
</header>
<hr class="hide" />
<section id="feature">
<div class="wrapper">
<h1>REST APIs</h1><p>After working through this guide you will:</p>
<ul>
<li>know about the thinking behind REST APIs</li>
<li>be able to configure your existing Rails controllers to offer resources as JSON</li>
<li>be able to set up an API for your Rails app that is separate from existing controllers</li>
</ul>
<div class="interstitial repo"><p>You can study the <a href="https://github.com/backend-development/api_sample_app">code</a> and try out <a href="https://iou-brigitte.herokuapp.com">the demo</a> for the example described here.</p></div>
<nav id="subCol">
<h3 class="chapter">
<picture>
<!-- Using the `source` HTML tag to set the dark theme image -->
<source
srcset="images/icon_book-close-bookmark-1-wht.svg"
media="(prefers-color-scheme: dark)"
/>
<img src="images/icon_book-close-bookmark-1.svg" alt="Chapter Icon" />
</picture>
Chapters
</h3>
<ol class="chapters">
<li><a href="#what-is-an-api">What is an API</a>
<ul>
<li><a href="#soap-rest-and-graphql">SOAP, REST and GraphQL</a></li>
<li><a href="#api-separates-two-layers">API separates two layers</a></li>
<li><a href="#api-for-many-different-clients">API for many different clients</a></li>
<li><a href="#backend-offers-more-than-an-api">Backend offers more than an API</a></li>
</ul></li>
<li><a href="#rest">REST</a>
<ul>
<li><a href="#urls">URLS</a></li>
<li><a href="#hateoas">HATEOAS</a></li>
<li><a href="#http-methods-and-status-codes">HTTP Methods and Status Codes</a></li>
<li><a href="#multiple-representations">Multiple Representations</a></li>
<li><a href="#statelessness">Statelessness</a></li>
<li><a href="#json-api">JSON API</a></li>
<li><a href="#exploring-a-rest-api">Exploring a REST API</a></li>
<li><a href="#testing-and-documenting-a-rest-api">Testing and Documenting a REST API</a></li>
</ul></li>
<li><a href="#rails-rest-api-in-with-existing-controllers">Rails: REST API in with existing Controllers</a>
<ul>
<li><a href="#api-for-the-sample-app">API for the sample app</a></li>
<li><a href="#creating-an-api-with-existing-controllers">creating an API with existing controllers</a></li>
<li><a href="#creating-json-with-erb-not-a-good-idea">creating JSON with erb - not a good idea</a></li>
<li><a href="#creating-json-with-jbuilder-a-better-idea">creating JSON with jbuilder - a better idea</a></li>
<li><a href="#authentication-and-the-api">Authentication and the API</a></li>
</ul></li>
<li><a href="#rails-stand-alone-rest-api">Rails: Stand Alone REST API</a>
<ul>
<li><a href="#setting-up-controllers">setting up controllers</a></li>
<li><a href="#creating-json-with-blueprinter">creating JSON with blueprinter</a></li>
</ul></li>
<li><a href="#see-also">See Also</a></li>
</ol>
</nav>
<hr>
</div>
</section>
<main id="container">
<div class="wrapper">
<div id="mainCol">
<div class='slide'>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-0' href='slides_rest-api.html#/0'>◻</a></p>
<h2 id="what-is-an-api"><a class="anchorlink" href="#what-is-an-api"><span>1</span> What is an API</a></h2><p>API stands for "Application Programming Interface". It is a set of clearly defined methods
of communication with a software component. So the objects and methods exposed by a library
form an API.</p><p>In Web development the acronym API is most
commonly used when the software component in question runs on a different server on the
Internet and is accessed via HTTP.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-1' href='slides_rest-api.html#/1'>◻</a></p>
<h3 id="soap-rest-and-graphql"><a class="anchorlink" href="#soap-rest-and-graphql"><span>1.1</span> SOAP, REST and GraphQL</a></h3><p>Currently three main API Styles are used on the Web:</p>
<ul>
<li><strong>SOAP</strong>, designed 1998 at Microsoft,
uses XML and POST requests to make "remote procedure calls"</li>
<li><strong>REST</strong>, described in 2000,
uses different HTTP Methods and Status Messages to access "resources"</li>
<li><strong>GraphQL</strong>, released 2015 by Facebook,
uses POST requests, it's own query language and JSON</li>
</ul>
<p>This Guide is concerned with REST, there is a second guide for <a href="/graphql-api.html">GraphQL</a>. SOAP
is rearely offered with Rails, but there is a <a href="https://github.com/savonrb/savon">soap client</a> in
ruby.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-2' href='slides_rest-api.html#/2'>◻</a></p>
<h3 id="api-separates-two-layers"><a class="anchorlink" href="#api-separates-two-layers"><span>1.2</span> API separates two layers</a></h3><p>Please note that any of the API styles can be used
with any backend, frontend, persistance layers:</p>
<ul>
<li>You can build a REST in front of a PHP backend using MongoDB as the database and use it from a frontend written with jQuery.</li>
<li>You can build a GraphQL API for a Rails backend using MySQL as the database and build the frontend with React.</li>
<li>You can use a CMS like Strapi through a REST API from a React frontend</li>
</ul>
<p>That's kind of the point of an API: to allow different technologies
on both sides of the API.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-3' href='slides_rest-api.html#/3'>◻</a></p>
<h3 id="api-for-many-different-clients"><a class="anchorlink" href="#api-for-many-different-clients"><span>1.3</span> API for many different clients</a></h3><p>Using an API you can build a common backend for different cleints:</p>
<ul>
<li>one client could be a native mobile app for iOS</li>
<li>another client could be a natvie mobile app for Android</li>
<li>a third client could be a Single Page App written with React</li>
</ul>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-4' href='slides_rest-api.html#/4'>◻</a></p>
<h3 id="backend-offers-more-than-an-api"><a class="anchorlink" href="#backend-offers-more-than-an-api"><span>1.4</span> Backend offers more than an API</a></h3><p>Your "backend" might still offer some "Server Rendered HTML" besides
the API:</p>
<ul>
<li>Documentation for the API (e.g. swagger, see below)</li>
<li>AdminPanel (e.g. created automatically by rails_admin)</li>
</ul>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-5' href='slides_rest-api.html#/5'>◻</a></p>
<h2 id="rest"><a class="anchorlink" href="#rest"><span>2</span> REST</a></h2><p>The acronym REST was coined by <a href="https://roy.gbiv.com/">Roy Fielding</a> in his dissertation. When describing
the architecture of the web, and what made it so successful on a technical level,
he described this architecture as "Representational State Transfer" (REST).</p><p>This Acronym was later picked up to describe a certain style of API,
and to distinguish such APIs from SOAP APIs.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-6' href='slides_rest-api.html#/6'>◻</a></p>
<p>A REST API allows to access and manipulate textual representations of <strong>Web resources</strong> using HTTP Methods and stateless operations.</p><p>"Web resources" were first defined on the World Wide Web as documents or files identified by their URLs, but today they have a much more generic and abstract definition encompassing every thing or entity that can be identified, named, addressed or handled, in any way whatsoever, on the Web.</p><p><a href="https://www.infoq.com/articles/rest-introduction">Tilkov(2007)</a> gives a brief introduction to REST. The main points are:</p>
<ol>
<li> Give every resource a unique URL</li>
<li> “Hypermedia as the engine of application state” (HATEOAS) - use URLs to reference other resources (not just ids)</li>
<li> Use HTTP Methods (and Status Codes) as intended.</li>
<li> One resource can have multiple representations, for example HTML, JSON and XML</li>
<li> Communicate statelessly - if possible!</li>
</ol>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-7' href='slides_rest-api.html#/7'>◻</a></p>
<h3 id="urls"><a class="anchorlink" href="#urls"><span>2.1</span> URLS</a></h3><p>Give every resource a unique URL.
Please note that REST does not demand a certain form of URL.
While URLs with no parameters are often used:</p><div class="interstitial code">
<pre><code class="highlight plaintext">https://example.com/users/
https://example.com/users/1/
https://example.com/users/2/
https://example.com/users/3/
</code></pre>
<button class="clipboard-button" data-clipboard-text="https://example.com/users/
https://example.com/users/1/
https://example.com/users/2/
https://example.com/users/3/
">Copy</button>
</div>
<p>it is just as restful to use parameters:</p><div class="interstitial code">
<pre><code class="highlight plaintext">https://example.com/users.php
https://example.com/users.php?id=1
https://example.com/users.php?id=2
https://example.com/users.php?id=3
</code></pre>
<button class="clipboard-button" data-clipboard-text="https://example.com/users.php
https://example.com/users.php?id=1
https://example.com/users.php?id=2
https://example.com/users.php?id=3
">Copy</button>
</div>
<p>In REST, the URLs correspond to resources, which are represented by nouns.
This is a difference to SOAP, there there is typically just one endpoint:</p><div class="interstitial code">
<pre><code class="highlight plaintext">https://example.com/soap/router/
</code></pre>
<button class="clipboard-button" data-clipboard-text="https://example.com/soap/router/
">Copy</button>
</div>
<p>Through this endpoint you can access methods like <code>getUserData()</code> or <code>deleteUser()</code>.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-8' href='slides_rest-api.html#/8'>◻</a></p>
<h3 id="hateoas"><a class="anchorlink" href="#hateoas"><span>2.2</span> HATEOAS</a></h3><p>“Hypermedia as the engine of application state” means that a client interacts with a network application entirely through hypermedia, and needs no prior knowledge of URLs.</p><p>If an API returns the following JSON:</p><div class="interstitial code">
<pre><code class="highlight js"><span class="p">{</span>
<span class="dl">"</span><span class="s2">id</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">1</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">name</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Example User</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">email</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">example@railstutorial.org</span><span class="dl">"</span>
<span class="dl">"</span><span class="s2">profile_pics</span><span class="dl">"</span><span class="p">:</span> <span class="p">[</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">5</span> <span class="p">]</span>
<span class="p">}</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="{
"id": "1",
"name": "Example User",
"email": "example@railstutorial.org"
"profile_pics": [ 2, 5 ]
}
">Copy</button>
</div>
<p>Then the Client needs to know how to get profile_pics from the API.
For example because the developer read the docs.</p><p>HATEOAS demands that the full URL is used to refer to other resources:</p><div class="interstitial code">
<pre><code class="highlight js"><span class="p">{</span>
<span class="dl">"</span><span class="s2">id</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">1</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">name</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Example User</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">email</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">example@railstutorial.org</span><span class="dl">"</span>
<span class="dl">"</span><span class="s2">profile_pics</span><span class="dl">"</span><span class="p">:</span> <span class="p">[</span>
<span class="dl">"</span><span class="s2">https://sample.com/api/profile/pictures/2</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">https://sample.com/api/profile/pictures/5</span><span class="dl">"</span>
<span class="p">]</span>
<span class="p">}</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="{
"id": "1",
"name": "Example User",
"email": "example@railstutorial.org"
"profile_pics": [
"https://sample.com/api/profile/pictures/2",
"https://sample.com/api/profile/pictures/5"
]
}
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-9' href='slides_rest-api.html#/9'>◻</a></p>
<h3 id="http-methods-and-status-codes"><a class="anchorlink" href="#http-methods-and-status-codes"><span>2.3</span> HTTP Methods and Status Codes</a></h3><p>Use HTTP Methods (and Status Codes) as intended.</p><p>Regarding the HTTP Methods there are two important distinctions:</p>
<ul>
<li>the GET and HEAD methods should take no other action than retrieval. These methods ought to be considered <strong>safe</strong>.</li>
<li>The methods GET, HEAD, PUT and DELETE are idempotent: repeating the request will not change the end result (aside from error or expiration issues)</li>
</ul>
<p>The definition of the <a href="https://www.rfc-editor.org/rfc/rfc9110.html#methods">Methods</a> in HTTP is a quick read, and well worth it!</p><p>References for status codes:</p>
<ul>
<li><a href="https://httpstatuses.com/422">Status codes</a></li>
<li><a href="https://http.cat/">Status cats</a></li>
</ul>
<p>When building a REST API, the HTTP Protocol already defines a lot
about that API. There is no need to come up with a way to delete
a resource, or to indicate failure. HTTP already offers the DELETE method
and status codes that indicate errors.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-10' href='slides_rest-api.html#/10'>◻</a></p>
<h3 id="multiple-representations"><a class="anchorlink" href="#multiple-representations"><span>2.4</span> Multiple Representations</a></h3><p>The same resource can be available in different formats.
There are two common ways of requesting different formats:</p><p>With the HTTP Header <code>Accept</code>:</p><div class="interstitial code">
<pre><code class="highlight http"><span class="nf">GET</span> <span class="nn">/mini/person/83</span> <span class="k">HTTP</span><span class="o">/</span><span class="m">1.1</span>
<span class="na">Host</span><span class="p">:</span> <span class="s">example.com</span>
<span class="na">Accept</span><span class="p">:</span> <span class="s">application/xml</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="GET /mini/person/83 HTTP/1.1
Host: example.com
Accept: application/xml
">Copy</button>
</div>
<p>Or by adding an "extension" as part of the URL:</p><div class="interstitial code">
<pre><code class="highlight plaintext">https://example.com/mini/person/83.html
https://example.com/mini/person/83.xml
https://example.com/mini/person/83.json
</code></pre>
<button class="clipboard-button" data-clipboard-text="https://example.com/mini/person/83.html
https://example.com/mini/person/83.xml
https://example.com/mini/person/83.json
">Copy</button>
</div>
<p>The three different versions of person number 83 might look
like this: the HTML web page:</p><div class="interstitial code">
<pre><code class="highlight html"><span class="nt"><h1></span>Details zu einer Person<span class="nt"></h1></span>
<span class="nt"><p><img</span> <span class="na">src=</span><span class="s">"https://example.com/mini/profil/edvard_1_2.jpg"</span> <span class="nt">/></span>
Herr Edvard Paul Scissorhands hat insgesamt 4 Werke in dieser Datenbank.
Er hat den Usernamen fhs123.<span class="nt"></p></span>
<span class="nt"><ul></span>
<span class="nt"><li><a</span> <span class="na">href=</span><span class="s">'https://example.com/mini/werk/24'</span><span class="nt">></span>The Thin Red Line<span class="nt"></a></li></span>
<span class="nt"><li><a</span> <span class="na">href=</span><span class="s">'https://example.com/mini/werk/50'</span><span class="nt">></span>Der böse Wolf<span class="nt"></a></li></span>
<span class="nt"><li><a</span> <span class="na">href=</span><span class="s">'https://example.com/mini/werk/83'</span><span class="nt">></span>nimm zwei, schatz<span class="nt"></a></li></span>
<span class="nt"><li><a</span> <span class="na">href=</span><span class="s">'https://example.com/mini/werk/303'</span><span class="nt">></span>the neighbour.<span class="nt"></a></li></span>
<span class="nt"></ul></span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="<h1>Details zu einer Person</h1>
<p><img src="https://example.com/mini/profil/edvard_1_2.jpg" />
Herr Edvard Paul Scissorhands hat insgesamt 4 Werke in dieser Datenbank.
Er hat den Usernamen fhs123.</p>
<ul>
<li><a href='https://example.com/mini/werk/24'>The Thin Red Line</a></li>
<li><a href='https://example.com/mini/werk/50'>Der böse Wolf</a></li>
<li><a href='https://example.com/mini/werk/83'>nimm zwei, schatz</a></li>
<li><a href='https://example.com/mini/werk/303'>the neighbour.</a></li>
</ul>
">Copy</button>
</div>
<p>For an API the same resource might be represented as XML:</p><div class="interstitial code">
<pre><code class="highlight xml"><span class="nt"><person></span>
<span class="nt"><image</span> <span class="na">ref=</span><span class="s">'https://example.com/mini/profil/edvard_1_2.jpg'</span> <span class="nt">/></span>
<span class="nt"><vorname></span>Edvard<span class="nt"></vorname></span>
<span class="nt"><nachname></span>Scissorhands<span class="nt"></nachname></span>
<span class="nt"><username></span>fhs123<span class="nt"></username></span>
<span class="nt"><werke></span>
<span class="nt"><werk</span> <span class="na">ref=</span><span class="s">'https://example.com/mini/werk/24'</span><span class="nt">></span>The Thin Red Line<span class="nt"></werk></span>
<span class="nt"><werk</span> <span class="na">ref=</span><span class="s">'https://example.com/mini/werk/50'</span><span class="nt">></span>Der böse Wolf<span class="nt"></werk></span>
<span class="nt"><werk</span> <span class="na">ref=</span><span class="s">'https://example.com/mini/werk/83'</span><span class="nt">></span>nimm zwei, schatz<span class="nt"></werk></span>
<span class="nt"><werk</span> <span class="na">ref=</span><span class="s">'https://example.com/mini/werk/303'</span><span class="nt">></span>the neighbour.<span class="nt"></werk></span>
<span class="nt"></werke></span>
<span class="nt"></person></span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="<person>
<image ref='https://example.com/mini/profil/edvard_1_2.jpg' />
<vorname>Edvard</vorname>
<nachname>Scissorhands</nachname>
<username>fhs123</username>
<werke>
<werk ref='https://example.com/mini/werk/24'>The Thin Red Line</werk>
<werk ref='https://example.com/mini/werk/50'>Der böse Wolf</werk>
<werk ref='https://example.com/mini/werk/83'>nimm zwei, schatz</werk>
<werk ref='https://example.com/mini/werk/303'>the neighbour.</werk>
</werke>
</person>
">Copy</button>
</div>
<p>or as JSON:</p><div class="interstitial code">
<pre><code class="highlight json"><span class="p">{</span><span class="nl">"image"</span><span class="p">:</span><span class="s2">"https://example.com/mini/profil/edvard_1_2.jpg"</span><span class="p">,</span><span class="w">
</span><span class="nl">"vorname"</span><span class="p">:</span><span class="s2">"Edvard"</span><span class="p">,</span><span class="w">
</span><span class="nl">"nachname"</span><span class="p">:</span><span class="s2">"Scissorhands"</span><span class="p">,</span><span class="w">
</span><span class="nl">"werk"</span><span class="p">:[</span><span class="w">
</span><span class="p">{</span><span class="nl">"titel"</span><span class="p">:</span><span class="s2">"The Thin Red Line"</span><span class="p">,</span><span class="w">
</span><span class="nl">"url"</span><span class="p">:</span><span class="s2">"https://example.com/mini/werk/24"</span><span class="p">},</span><span class="w">
</span><span class="p">{</span><span class="nl">"titel"</span><span class="p">:</span><span class="s2">"Der böse Wolf"</span><span class="p">,</span><span class="w">
</span><span class="nl">"url"</span><span class="p">:</span><span class="s2">"https://example.com/mini/werk/50"</span><span class="p">},</span><span class="w">
</span><span class="p">{</span><span class="nl">"titel"</span><span class="p">:</span><span class="s2">"nimm zwei, schatz"</span><span class="p">,</span><span class="w">
</span><span class="nl">"url"</span><span class="p">:</span><span class="s2">"https://example.com/mini/werk/83"</span><span class="p">},</span><span class="w">
</span><span class="p">{</span><span class="nl">"titel"</span><span class="p">:</span><span class="s2">"the neighbour."</span><span class="p">,</span><span class="w">
</span><span class="nl">"url"</span><span class="p">:</span><span class="s2">"https://example.com/mini/werk/303"</span><span class="p">}]}</span><span class="w">
</span></code></pre>
<button class="clipboard-button" data-clipboard-text="{"image":"https://example.com/mini/profil/edvard_1_2.jpg",
"vorname":"Edvard",
"nachname":"Scissorhands",
"werk":[
{"titel":"The Thin Red Line",
"url":"https://example.com/mini/werk/24"},
{"titel":"Der böse Wolf",
"url":"https://example.com/mini/werk/50"},
{"titel":"nimm zwei, schatz",
"url":"https://example.com/mini/werk/83"},
{"titel":"the neighbour.",
"url":"https://example.com/mini/werk/303"}]}
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-11' href='slides_rest-api.html#/11'>◻</a></p>
<h3 id="statelessness"><a class="anchorlink" href="#statelessness"><span>2.5</span> Statelessness</a></h3><p>Tilkov wirtes: "REST mandates that state be either turned into resource state, or kept on the client. In other words, a server should not have to retain some sort of communication state for any of the clients it communicates with beyond a single request."</p><p>This is important for performance and scalability.
Statelessness makes caching easy. And in a scenario with multiple servers behind a load balancer, having no state on the server means that the application will work when a client's requests are routed to different servers.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-12' href='slides_rest-api.html#/12'>◻</a></p>
<h3 id="json-api"><a class="anchorlink" href="#json-api"><span>2.6</span> JSON API</a></h3><p>When an API returns JSON data this could take many forms.
The <a href="https://jsonapi.org/">json:api specification</a> is a well thought out
convention for this.</p><p>It is imlements the HATEOS aspect of REST and defines a way to do associations and aggregation.</p><p>For smaller projects it might be overkill.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-13' href='slides_rest-api.html#/13'>◻</a></p>
<h3 id="exploring-a-rest-api"><a class="anchorlink" href="#exploring-a-rest-api"><span>2.7</span> Exploring a REST API</a></h3><p>You can explor a REST with several tool:</p>
<ul>
<li><a href="https://curl.haxx.se/docs/manual.html">curl</a> is a command line tool for sending HTTP requests</li>
<li>developer tools in the browser can edit "re-send" a request, or <a href="https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor/request_list#Context_menu">copy as curl</a></li>
<li><a href="https://hoppscotch.io/">hoppscotch</a> is a browser based REST client</li>
<li><a href="https://insomnia.rest/download">insomnia</a> is a client you install as a native app</li>
</ul>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-14' href='slides_rest-api.html#/14'>◻</a></p>
<h3 id="testing-and-documenting-a-rest-api"><a class="anchorlink" href="#testing-and-documenting-a-rest-api"><span>2.8</span> Testing and Documenting a REST API</a></h3><p><a href="https://swagger.io/resources/open-api/">The OpenAPI Specification</a> is a way for
specifying and documenting REST APIs. There are a lot of tools available around it
for many different programming languages.</p><p>For Rails I recommend the gem <code>rswag</code>: with rswag you write tests (specs) for your
api, and the documentation is generated from the (successful) tests.
There is also a web-ui to read the documentation and run API requests -
<a href="https://iou-brigitte.herokuapp.com/api-docs/index.html">Swagger Web UI in the example app</a></p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-15' href='slides_rest-api.html#/15'>◻</a></p>
<h2 id="rails-rest-api-in-with-existing-controllers"><a class="anchorlink" href="#rails-rest-api-in-with-existing-controllers"><span>3</span> Rails: REST API in with existing Controllers</a></h2><p>Rails is equipped to not just create HTML as output, but to easily
offer other representations as well.</p><p>When you look at <code>rails routes</code> you can see that the routes created by
<code>resource :user</code> could contain an optional <code>format</code>:</p><div class="interstitial code">
<pre><code class="highlight plaintext"> Prefix Verb URI Pattern Controller#Action
root GET / static_pages#home
users GET /users(.:format) users#index
user GET /users/:id(.:format) users#show
</code></pre>
<button class="clipboard-button" data-clipboard-text=" Prefix Verb URI Pattern Controller#Action
root GET / static_pages#home
users GET /users(.:format) users#index
user GET /users/:id(.:format) users#show
">Copy</button>
</div>
<p>Only HTML is implemented by default. But we could use this feature
to have other formats:</p>
<ul>
<li><code>/users</code></li>
<li><code>/users.json</code></li>
<li><code>/users.xml</code></li>
<li><code>/users/1</code></li>
<li><code>/users/1.json</code></li>
<li><code>/users/1.xml</code></li>
</ul>
<p>When you try out accessing <code>/users/1.json</code> you get a response:</p><div class="interstitial code">
<pre><code class="highlight plaintext">406 Not Acceptable
Content-Length: 39
Content-Type: application/json; charset=utf-8
{"status":406,"error":"Not Acceptable"}
</code></pre>
<button class="clipboard-button" data-clipboard-text="406 Not Acceptable
Content-Length: 39
Content-Type: application/json; charset=utf-8
{"status":406,"error":"Not Acceptable"}
">Copy</button>
</div>
<p>This error message is meant for a
client expecting JSON data. It uses both the HTTP status code
and the JSON to indicate the error.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-16' href='slides_rest-api.html#/16'>◻</a></p>
<h3 id="api-for-the-sample-app"><a class="anchorlink" href="#api-for-the-sample-app"><span>3.1</span> API for the sample app</a></h3><p>The "Frontend 1" in the example app expects a very simple JSON structure:</p><p>To display one user, it loads from <code>/user/1.json</code> and expects
a single JSON object with three attributes:</p><div class="interstitial code">
<pre><code class="highlight plaintext">{
"id":1,
"name":"Example User",
"email":"example@railstutorial.org"
}
</code></pre>
<button class="clipboard-button" data-clipboard-text="{
"id":1,
"name":"Example User",
"email":"example@railstutorial.org"
}
">Copy</button>
</div>
<p>To display the table of users, it loads from <code>/users.json</code> and
expects a JSON array of objects like above:</p><div class="interstitial code">
<pre><code class="highlight plaintext">[
{
"id":2,
"name":"Precious Heaney",
"email":"example-1@railstutorial.org"
},
{
"id":3,
"name":"Warren Considine Sr.",
"email":"example-2@railstutorial.org"
}
]
</code></pre>
<button class="clipboard-button" data-clipboard-text="[
{
"id":2,
"name":"Precious Heaney",
"email":"example-1@railstutorial.org"
},
{
"id":3,
"name":"Warren Considine Sr.",
"email":"example-2@railstutorial.org"
}
]
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-17' href='slides_rest-api.html#/17'>◻</a></p>
<h3 id="creating-an-api-with-existing-controllers"><a class="anchorlink" href="#creating-an-api-with-existing-controllers"><span>3.2</span> creating an API with existing controllers</a></h3><p>The scaffold generator always adds handling JSON responses
to the actions of a controller.</p><p>For handling just HTML only this code would be needed in the
create action:</p><div class="interstitial code">
<pre><code class="highlight plaintext"> # POST /users
def create
@user = User.new(user_params)
if @user.save
redirect_to @user, notice: 'User was successfully created.'
else
render :new
end
end
end
</code></pre>
<button class="clipboard-button" data-clipboard-text=" # POST /users
def create
@user = User.new(user_params)
if @user.save
redirect_to @user, notice: 'User was successfully created.'
else
render :new
end
end
end
">Copy</button>
</div>
<p>But the scaffold generator also adds <code>resond_to</code> and <code>format</code> commands,
to handle json differently from html:</p><div class="interstitial code">
<pre><code class="highlight plaintext"> # POST /users
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html {
redirect_to @user, notice: 'User was successfully created.'
}
format.json {
render :show, status: :created, location: @user
}
else
format.html {
render :new
}
format.json {
render json: @user.errors, status: :unprocessable_entity
}
end
end
end
</code></pre>
<button class="clipboard-button" data-clipboard-text=" # POST /users
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html {
redirect_to @user, notice: 'User was successfully created.'
}
format.json {
render :show, status: :created, location: @user
}
else
format.html {
render :new
}
format.json {
render json: @user.errors, status: :unprocessable_entity
}
end
end
end
">Copy</button>
</div>
<p>so in the controller we might not need to change anything to add the
API, only in the view.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-18' href='slides_rest-api.html#/18'>◻</a></p>
<h3 id="creating-json-with-erb-not-a-good-idea"><a class="anchorlink" href="#creating-json-with-erb-not-a-good-idea"><span>3.3</span> creating JSON with erb - not a good idea</a></h3><p>We could create views using erb in <code>app/views/users/show.json.erb</code>:</p><div class="interstitial code">
<pre><code class="highlight plaintext">{
"id": <%= @user.id %>,
"name": "<%= @user.name %>",
"email": "<%= @user.email %>"
}
</code></pre>
<button class="clipboard-button" data-clipboard-text="{
"id": <%= @user.id %>,
"name": "<%= @user.name %>",
"email": "<%= @user.email %>"
}
">Copy</button>
</div>
<p>and <code>app/views/users/index.json.erb</code>:</p><div class="interstitial code">
<pre><code class="highlight plaintext">[
<%
@users.each_with_index do |user| %>
{
"id": <%= user.id %>,
"name": "<%= user.name %>",
"email": "<%= user.email %>"
},
<% end %>
]
</code></pre>
<button class="clipboard-button" data-clipboard-text="[
<%
@users.each_with_index do |user| %>
{
"id": <%= user.id %>,
"name": "<%= user.name %>",
"email": "<%= user.email %>"
},
<% end %>
]
">Copy</button>
</div>
<p>But wait, there's a problem: there is a comma after each object,
but there should be no comma after the last.</p><div class="interstitial code">
<pre><code class="highlight plaintext">[
<%
max = @users.length - 1
@users.each_with_index do |user,i| %>
{
"id": <%= user.id %>,
"name": "<%= user.name %>",
"email": "<%= user.email %>"
}
<%= if i < max then ',' end %>
<% end %>
]
</code></pre>
<button class="clipboard-button" data-clipboard-text="[
<%
max = @users.length - 1
@users.each_with_index do |user,i| %>
{
"id": <%= user.id %>,
"name": "<%= user.name %>",
"email": "<%= user.email %>"
}
<%= if i < max then ',' end %>
<% end %>
]
">Copy</button>
</div>
<p>And wait, there's another problem: What happens
if a users name contains a quote? For example <kbd>Jack "the Ripper"</kbd>.
That would break our current view, because we don't do proper escaping.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-19' href='slides_rest-api.html#/19'>◻</a></p>
<h3 id="creating-json-with-jbuilder-a-better-idea"><a class="anchorlink" href="#creating-json-with-jbuilder-a-better-idea"><span>3.4</span> creating JSON with jbuilder - a better idea</a></h3><p>Rails 5 comes with the gem <code>jbuilder</code> which helps you create JSON, and
which handles all the escaping and formatting correctly.</p><p>We need to name the view <code>app/views/users/show.json.jbuilder</code>,
and then can use the the following code to extract three properties
from the user object:</p><div class="interstitial code">
<pre><code class="highlight plaintext">json.id @user.id
json.name @user.name
json.email @user.email
</code></pre>
<button class="clipboard-button" data-clipboard-text="json.id @user.id
json.name @user.name
json.email @user.email
">Copy</button>
</div>
<p>There is also a shorthand for this:</p><div class="interstitial code">
<pre><code class="highlight plaintext">json.extract! @user, :id, :name, :email
</code></pre>
<button class="clipboard-button" data-clipboard-text="json.extract! @user, :id, :name, :email
">Copy</button>
</div>
<p>For the index view we want to create a JSON array.
In <code>app/views/users/index.json.jbuilder</code> we write:</p><div class="interstitial code">
<pre><code class="highlight plaintext">json.array! @users do |user|
json.extract! user, :id, :name, :email
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="json.array! @users do |user|
json.extract! user, :id, :name, :email
end
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-20' href='slides_rest-api.html#/20'>◻</a></p>
<h3 id="authentication-and-the-api"><a class="anchorlink" href="#authentication-and-the-api"><span>3.5</span> Authentication and the API</a></h3><p>All the authentication and access control we built into the
rails app before is still applicable to the API and JSON views.
If the "Frontend" that is using our API is displayed in a browser,
the handling of cookies and the session is exactly the same as before.</p><p>If the "Frontend" is not in a browser, but is a native mobile app or
just another server side job, we have to use an alternative to cookies.
<a href="https://backend-development.github.io/rails_authentication.html#how-to-add-state-to-http">JSON Web Tokens</a> are a solution.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-21' href='slides_rest-api.html#/21'>◻</a></p>
<h2 id="rails-stand-alone-rest-api"><a class="anchorlink" href="#rails-stand-alone-rest-api"><span>4</span> Rails: Stand Alone REST API</a></h2><p>To create a stand alone API we define new, separate routes under <code>/api/v1</code>.</p><div class="interstitial code">
<pre><code class="highlight plaintext">namespace :api do
namespace :v1 do
resources :users, only: [:index, :create, :show, :update, :destroy]
end
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="namespace :api do
namespace :v1 do
resources :users, only: [:index, :create, :show, :update, :destroy]
end
end
">Copy</button>
</div>
<p>we will be using the <code>blueprint</code> gem for creating JSON output. It does not comply with
the JSON-API specification, but it is fine for smaller projects.</p><div class="interstitial code">
<pre><code class="highlight plaintext">bundle add 'blueprinter'
</code></pre>
<button class="clipboard-button" data-clipboard-text="bundle add 'blueprinter'
">Copy</button>
</div>
<p><strong>Beware</strong>: After adding a gem you
need to restart the rails server!</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-22' href='slides_rest-api.html#/22'>◻</a></p>
<h3 id="setting-up-controllers"><a class="anchorlink" href="#setting-up-controllers"><span>4.1</span> setting up controllers</a></h3><p>After we defined the routes, we next need to create a controller.
As we are setting up a new hierarchy of controllers that will only
concerned with the API, it makes sense to inhert from <code>ActionController::API</code>,
not from <code>ActionController::Base</code>.</p><p>All the "normal" controllers first inhert from <code>ApplicationController</code>. We
will build a similar structure for the api controllers, the will inhert from
<code>Api::V1::BaseController</code>:</p><div class="interstitial code">
<pre><code class="highlight plaintext"># app/controllers/api/v1/base_controller.rb
class Api::V1::BaseController < ActionController::API
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="# app/controllers/api/v1/base_controller.rb
class Api::V1::BaseController < ActionController::API
end
">Copy</button>
</div>
<p>The users controller is the one that's actually called by the route:</p><div class="interstitial code">
<pre><code class="highlight plaintext"># app/controllers/api/v1/users_controller.rb
class Api::V1::UsersController < Api::V0::BaseController
def index
users = User.all
render json: ...
end
def show
user = User.find(params[:id])
render json: ...
end
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="# app/controllers/api/v1/users_controller.rb
class Api::V1::UsersController < Api::V0::BaseController
def index
users = User.all
render json: ...
end
def show
user = User.find(params[:id])
render json: ...
end
end
">Copy</button>
</div>
<p>The controller loads the right model, and then needs to calls a <strong>serializer</strong> to
do the actual rendering of the json data. We will create this serializer next.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-23' href='slides_rest-api.html#/23'>◻</a></p>
<h3 id="creating-json-with-blueprinter"><a class="anchorlink" href="#creating-json-with-blueprinter"><span>4.2</span> creating JSON with blueprinter</a></h3><p>With the gem blueprinter the
serializers live in the <code>/app/blueprints</code> folder.</p><div class="interstitial code">
<pre><code class="highlight plaintext"># app/blueprints/user_blueprint.rb
class UserBlueprint < Blueprinter::Base
identifier :id
fields :name, :email
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="# app/blueprints/user_blueprint.rb
class UserBlueprint < Blueprinter::Base
identifier :id
fields :name, :email
end
">Copy</button>
</div>
<p>This serializer can be used both for single users and for arrays
of users. We can now complete the controller:</p><div class="interstitial code">
<pre><code class="highlight plaintext"># app/controllers/api/v1/users_controller.rb
class Api::V1::UsersController < Api::V0::BaseController
def index
users = User.all
render json: UserBlueprint.render(users)
end
def show
user = User.find(params[:id])
render json: UserBlueprint.render(user)
end
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="# app/controllers/api/v1/users_controller.rb
class Api::V1::UsersController < Api::V0::BaseController
def index
users = User.all
render json: UserBlueprint.render(users)
end
def show
user = User.find(params[:id])
render json: UserBlueprint.render(user)
end
end
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-24' href='slides_rest-api.html#/24'>◻</a></p>
<h2 id="see-also"><a class="anchorlink" href="#see-also"><span>5</span> See Also</a></h2>
<ul>
<li><a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm">Fielding, Roy(2000): Architectural Styles and the Design of Network-based Software Architectures</a>. Dissertation. University of California/Irvine, USA.</li>
<li><a href="https://martinfowler.com/articles/richardsonMaturityModel.html">Fowler (2010): Richardson Maturity Model</a></li>
<li><a href="https://www.infoq.com/articles/rest-introduction">Tilkov(2007): A Brief Introduction to REST</a></li>
<li><a href="http://standards.rest/">standards.rest</a> a collection of standards that have developed around REST</li>
<li><a href="https://edgeguides.rubyonrails.org/action_controller_overview.html#rendering-xml-and-json-data">Rails Guide: Rendering JSON in Action Controller Overview</a></li>
<li><a href="https://edgeguides.rubyonrails.org/api_app.html">Rails Guide: Using Rails for API-only Applications</a></li>
<li><a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">Methods HTTP/1.0</a></li>
<li><a href="https://httpstatuses.com/422">Status codes</a></li>
<li><a href="https://github.com/nsarno/knock">gem knock</a> for token based authentication for API only Rails apps</li>
<li><a href="https://api-platform.com/">API Platform</a> to build REST + GraphQL APIs in PHP</li>
<li>Halliday(2016): <a href="https://blog.codeship.com/producing-documentation-for-your-rails-api/">Producing Documentation for Your Rails API</a> for a discussion of automatic methods of documentation generation.</li>
</ul>
</div>
</div>
</div>
</main>
<hr class="hide" />
<footer id="page_footer">
<div class="wrapper">
<p class="copyright">published under <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/at/deed.de">creative commons by-nc-sa</a> in 2012-2025 by <a href="https://brigitte-jellinek.at">Brigitte Jellinek</a>.
</p>
<p>If you want to contribute: <a href="https://github.com/backend-development/backend-development-textbook/fork">fork the source on github</a>
</p>
<p>Favicon "backend development" by Arkinasi from <a href="https://thenounproject.com/browse/icons/term/backend-development/" target="_blank" title="backend development Icons">Noun Project</a> (CC BY 3.0)</p>
</div>
</footer>
</body>
</html>