-
Notifications
You must be signed in to change notification settings - Fork 16
/
chap-web_services.lyx
4467 lines (3073 loc) · 71.9 KB
/
chap-web_services.lyx
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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#LyX 1.6.7 created this file. For more info see http://www.lyx.org/
\lyxformat 345
\begin_document
\begin_header
\textclass book
\use_default_options false
\language english
\inputencoding auto
\font_roman default
\font_sans default
\font_typewriter default
\font_default_family default
\font_sc false
\font_osf false
\font_sf_scale 100
\font_tt_scale 100
\graphics default
\paperfontsize default
\spacing single
\use_hyperref false
\papersize default
\use_geometry false
\use_amsmath 1
\use_esint 1
\cite_engine basic
\use_bibtopic false
\paperorientation portrait
\secnumdepth 3
\tocdepth 3
\paragraph_separation indent
\defskip medskip
\quotes_language english
\papercolumns 1
\papersides 1
\paperpagestyle default
\tracking_changes false
\output_changes false
\author ""
\author ""
\end_header
\begin_body
\begin_layout Chapter
RESTful Web Services
\begin_inset CommandInset label
LatexCommand label
name "cha:Web-Services"
\end_inset
\end_layout
\begin_layout Standard
Many web applications today offer an API
\begin_inset Foot
status open
\begin_layout Plain Layout
Application Programming Interface
\end_layout
\end_inset
that allows others to extend the functionality of the application.
An API is a set of exposed functions that is meant to allow third parties
to reuse elements of the application.
There is a number of sites that catalog the available APIs, such as Programmabl
eWeb (see
\begin_inset Flex URL
status open
\begin_layout Plain Layout
http://www.programmableweb.com/
\end_layout
\end_inset
).
An example of a site that has combined the GoogleMaps and Flickr APIs is
FlickrVision.com
\begin_inset Foot
status open
\begin_layout Plain Layout
\begin_inset CommandInset href
LatexCommand href
name "http://flickrvision.com/"
target "http://flickrvision.com/"
\end_inset
\end_layout
\end_inset
.
FlickrVision allows users to visualize where in the world recent photos
have been taken by combining the geolocation information embedded in the
photos and the mapping system of GoogleMaps.
This is just one example of an API mashup, and there are countless other
examples.
\end_layout
\begin_layout Section
Some Background on REST
\end_layout
\begin_layout Standard
Before we dive into the details of building a RESTful API with Lift, let's
start by discussing a little about REST and the protocol that it sits atop:
HTTP.
If you're already familiar with REST and HTTP, feel free to skip to the
implementation in Section
\begin_inset CommandInset ref
LatexCommand ref
reference "sec:A-Simple-API-pocketchange"
\end_inset
.
\end_layout
\begin_layout Subsection
A Little Bit about HTTP
\end_layout
\begin_layout Standard
As we build our web service, it will to be helpful to know a few things
about HTTP
\begin_inset Foot
status open
\begin_layout Plain Layout
Hypertext Transfer Protocol
\end_layout
\end_inset
requests and responses.
If you're comfortable with the Request-Response cycle then feel free to
jump to Section
\begin_inset CommandInset ref
LatexCommand ref
reference "sec:What-is-REST?"
\end_inset
to get down to business.
\end_layout
\begin_layout Standard
A simplification of how the web works is that clients, typically web browsers,
send HTTP Requests to servers, which respond with HTTP Responses.
Let's take a look at an exchange between a client and a server.
\end_layout
\begin_layout Standard
We're going to send a GET request to the URI
\begin_inset Flex URL
status open
\begin_layout Plain Layout
http://demo.liftweb.net/
\end_layout
\end_inset
using the
\family typewriter
cURL
\family default
utility.
We'll enable dumping the HTTP protocol header information so that you can
see all of the information associated with the request and response.
The cURL utility sends the output shown in Listing
\begin_inset CommandInset ref
LatexCommand ref
reference "lst:cURL-Output"
\end_inset
:
\end_layout
\begin_layout Standard
\begin_inset listings
inline false
status open
\begin_layout Plain Layout
\begin_inset Caption
\begin_layout Plain Layout
cURL Request
\begin_inset CommandInset label
LatexCommand label
name "lst:cURL-Output"
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Plain Layout
$ curl -v http://demo.liftweb.net/
\end_layout
\begin_layout Plain Layout
* About to connect() to demo.liftweb.net port 80 (#0)
\end_layout
\begin_layout Plain Layout
* Trying 64.27.11.183...
connected
\end_layout
\begin_layout Plain Layout
* Connected to demo.liftweb.net (64.27.11.183) port 80 (#0)
\end_layout
\begin_layout Plain Layout
> GET / HTTP/1.1
\end_layout
\begin_layout Plain Layout
> User-Agent: curl/7.19.0 (i386-apple-darwin9.5.0) libcurl/7.19.0 zlib/1.2.3
\end_layout
\begin_layout Plain Layout
> Host: demo.liftweb.net
\end_layout
\begin_layout Plain Layout
> Accept: */*
\end_layout
\end_inset
\end_layout
\begin_layout Standard
And gets the corresponding response, shown in Listing
\begin_inset CommandInset ref
LatexCommand ref
reference "lst:cURL-Response"
\end_inset
, from the server:
\end_layout
\begin_layout Standard
\begin_inset listings
inline false
status open
\begin_layout Plain Layout
\begin_inset Caption
\begin_layout Plain Layout
cURL Response
\begin_inset CommandInset label
LatexCommand label
name "lst:cURL-Response"
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Plain Layout
< HTTP/1.1 200 OK
\end_layout
\begin_layout Plain Layout
< Server: nginx/0.6.32
\end_layout
\begin_layout Plain Layout
< Date: Tue, 24 Mar 2009 20:52:55 GMT
\end_layout
\begin_layout Plain Layout
< Content-Type: text/html
\end_layout
\begin_layout Plain Layout
< Connection: keep-alive
\end_layout
\begin_layout Plain Layout
< Expires: Mon, 26 Jul 1997 05:00:00 GMT
\end_layout
\begin_layout Plain Layout
< Set-Cookie: JSESSIONID=5zrn24obipm5;Path=/
\end_layout
\begin_layout Plain Layout
< Content-Length: 8431
\end_layout
\begin_layout Plain Layout
< Cache-Control: no-cache; private; no-store;
\end_layout
\begin_layout Plain Layout
must-revalidate; max-stale=0; post-check=0; pre-check=0; max-age=0
\end_layout
\begin_layout Plain Layout
< Pragma: no-cache
\end_layout
\begin_layout Plain Layout
< X-Lift-Version: 0.11-SNAPSHOT
\end_layout
\begin_layout Plain Layout
<
\end_layout
\begin_layout Plain Layout
<?xml version="1.0" encoding="UTF-8"?>
\end_layout
\begin_layout Plain Layout
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
\end_layout
\begin_layout Plain Layout
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
\end_layout
\begin_layout Plain Layout
<html xmlns:lift="http://liftweb.net" xmlns="http://www.w3.org/1999/xhtml">
\end_layout
\begin_layout Plain Layout
<head>....
\end_layout
\end_inset
\end_layout
\begin_layout Standard
This seems pretty straightforward: we ask for a resource, and the server
returns it to us.
Take a look at the HTTP request.
We'd like to point out the method called, in this case a
\family typewriter
\begin_inset Quotes eld
\end_inset
GET
\begin_inset Quotes erd
\end_inset
,
\family default
and the
\family typewriter
\family default
URI,
\family typewriter
\family default
which is
\begin_inset Quotes eld
\end_inset
http://demo.liftweb.net/
\begin_inset Quotes erd
\end_inset
.
Method calls and addresses are what make the web work.
You can think of the web as a series of method calls on varying resources,
where the URI (Uniform Resource Identifier) identifies the resource upon
which the method will be called.
\end_layout
\begin_layout Standard
Methods are defined as part of the HTTP standard, and we'll use them in
our API.
In addition to
\family typewriter
GET
\family default
, the other HTTP methods are
\family typewriter
POST
\family default
,
\family typewriter
DELETE
\family default
,
\family typewriter
PUT
\family default
,
\family typewriter
HEAD
\family default
, and
\family typewriter
OPTIONS
\family default
.
You may also see methods referred to as actions or verbs.
In this chapter, we will focus on using
\family typewriter
GET
\family default
and
\family typewriter
PUT
\family default
for our API.
\end_layout
\begin_layout Standard
As do Requests, Responses come with a few important pieces of information.
Of note are the Response Code and the Entity Body.
In the above example, the Response Code is
\begin_inset Quotes eld
\end_inset
\family typewriter
200 OK
\family default
\begin_inset Quotes erd
\end_inset
and the Entity Body is the HTML content of the webpage, which is shown
as the last two lines starting with
\begin_inset Quotes eld
\end_inset
\family typewriter
<!DOCTYPE
\family default
.
\begin_inset Quotes erd
\end_inset
We've truncated the HTML content here to save space.
\end_layout
\begin_layout Standard
This was a quick overview of HTTP, but if you'd like to learn more, take
a look at the protocol definition found at
\begin_inset Foot
status open
\begin_layout Plain Layout
http://www.ietf.org/rfc/rfc2616.txt
\end_layout
\end_inset
.
We wanted to point out a few of the interesting parts of the cycle before
we got into building a REST API.
\end_layout
\begin_layout Subsection
Defining REST
\begin_inset CommandInset label
LatexCommand label
name "sec:What-is-REST?"
\end_inset
\end_layout
\begin_layout Standard
Roy Fielding defined REST in his dissertation
\begin_inset Foot
status open
\begin_layout Plain Layout
\begin_inset Flex URL
status open
\begin_layout Plain Layout
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm
\end_layout
\end_inset
\end_layout
\end_inset
and defined the main tenet of the architecture to be a uniform interface
to resources.
“Resources” refers to pieces of information that are named and have representat
ions.
Examples include an image, a Twitter status, or a timely item such as a
stock quote or the current temperature.
The uniform interface is supported by a set of constraints that include
the following:
\end_layout
\begin_layout Itemize
Statelessness of communication: This is built on top of HTTP, which is also
stateless.
\end_layout
\begin_layout Itemize
Client-server–style interaction: Again, just as the Web consists of browsers
talking to servers, REST discusses machines or applications talking to
servers in the same way.
\end_layout
\begin_layout Itemize
Support for caching: REST uses the caching headers of HTTP to support the
caching of resources.
\end_layout
\begin_layout Standard
These features are shared by both the web and by RESTful services.
REST adds additional constraints regarding interacting with resources:
\end_layout
\begin_layout Itemize
Naming: As we mentioned, a resource must be identified, and this is done
using URLs.
\end_layout
\begin_layout Itemize
Descriptive actions: Using the HTTP actions, GET, PUT, and DELETE makes
it obvious what action is being performed on the resource.
\end_layout
\begin_layout Itemize
URL addressability: URLs should allow for the addressing of representation
of a resource.
\end_layout
\begin_layout Standard
Fielding’s goal was to define a method that allowed machine-to-machine communica
tion to mimic that of browser-to-server communication and to take advantage
of HTTP as the underlying protocol.
\end_layout
\begin_layout Subsection
Comparing XML-RPC to REST Architectures
\end_layout
\begin_layout Standard
What, then, is the difference between a RESTful architecture and a traditional
RPC
\begin_inset Foot
status open
\begin_layout Plain Layout
Remote Procedure Call
\end_layout
\end_inset
architecture?
\end_layout
\begin_layout Standard
An RPC application follows a more traditional software development pattern.
It ignores most of the features offered by HTTP, such as the HTTP methods.
Instead, the scoping and data to be used by the call are contained in the
body of a POST request.
XML-RPC works similarly to the web for
\emph on
getting
\emph default
resources, but breaks from the HTTP model for everything else by overloading
the POST request.
You will often see the term SOAP when referring to an XML-RPC setup, because
SOAP permits the developer to define the action and the resource in the
body of the request and ignore the HTTP methods.
\end_layout
\begin_layout Standard
RESTful architectures embrace HTTP.
We're using the web; we may as well take advantage of it.
\end_layout
\begin_layout Section
A Simple API for PocketChange
\begin_inset CommandInset label
LatexCommand label
name "sec:A-Simple-API-pocketchange"
\end_inset
\end_layout
\begin_layout Standard
We're going to start with a simple example, so we'll only touch on some
of the more complex steps of building a web service, such as authentication
\begin_inset Index
status open
\begin_layout Plain Layout
HTTP ! authentication
\end_layout
\end_inset
\begin_inset Index
status open
\begin_layout Plain Layout
Authentication
\end_layout
\end_inset
and authorization.
If you would like to see the code involved in performing authentication
and authorization for our REST API, see Section
\begin_inset CommandInset ref
LatexCommand ref
reference "sub:HTTP-Authentication"
\end_inset
.
For the purposes of this example, we're going to model two calls to the
server: a GET request that responds with the details of an expense, and
a PUT to add a new expense.The URLs will be:
\end_layout
\begin_layout Itemize
A GET request sent to URI:
\end_layout
\begin_deeper
\begin_layout LyX-Code
http://www.pocketchangeapp.com/api/expense/<expense id>
\end_layout
\end_deeper
\begin_layout Itemize
A PUT request containing a new expense sent to URI:
\end_layout
\begin_deeper
\begin_layout LyX-Code
http://www.pocketchangeapp.com/api/account/<account id>
\end_layout
\end_deeper
\begin_layout Standard
\align center
\begin_inset Box Shadowbox
position "t"
hor_pos "c"
has_inner_box 1
inner_pos "t"
use_parbox 0
width "75col%"
special "none"
height "1in"
height_special "totalheight"
status open
\begin_layout Plain Layout
Note that a URL (Uniform Resource Locator) is a type of URI in which the
URI also serves to locate the resource on the web.
A URN (Uniform Resource Name) is another type of URI that provides a unique
name to a resource without specifying an actual location, though it may
look a lot like a URL.
For more information on the distinctions among URIs, see
\begin_inset Flex URL
status open
\begin_layout Plain Layout
http://en.wikipedia.org/wiki/Uniform_Resource_Name
\end_layout
\end_inset
.
\end_layout
\end_inset
\end_layout
\begin_layout Standard
We would like the REST API to support both XML and JSON for this data.
Additionally, we would like to support an Atom feed on an account so that
people can track expenses as they're added.
The URL for the Atom feed will be a GET of the form:
\end_layout
\begin_layout LyX-Code
http://www.pocketchangeapp.com/api/account/<account id>
\end_layout
\begin_layout Standard
In the next few sections we'll show how you can easily add support for these
methods and formats using Lift.
\end_layout
\begin_layout Section
Adding REST Helper Methods to our Entities
\end_layout
\begin_layout Standard
In order to simplify our REST handler code, we would like to add some helper
methods for our
\family typewriter
Expense
\family default
entity to support generation of both XML and JSON for our consumers.
We'll add these to a new
\family typewriter
RestFormatters
\family default
object inside the
\family typewriter
src/main/scala/com/pocketchangeapp/RestFormatters.scala
\family default
source file.
First, we add some common functionality in Listing
\begin_inset CommandInset ref
LatexCommand ref
reference "lst:Common-Expense-REST-helpers"
\end_inset
by adding several helper methods for computing REST header values.
\end_layout
\begin_layout Standard
\begin_inset listings
inline false
status open
\begin_layout Plain Layout
\begin_inset Caption
\begin_layout Plain Layout
Common Expense REST Helpers
\begin_inset CommandInset label
LatexCommand label
name "lst:Common-Expense-REST-helpers"
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Plain Layout
/* The REST timestamp format.
Not threadsafe, so we create
\end_layout
\begin_layout Plain Layout
* a new one each time.
*/
\end_layout
\begin_layout Plain Layout
def timestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
\end_layout
\begin_layout Plain Layout
\end_layout
\begin_layout Plain Layout
// A simple helper to generate the REST ID of an Expense
\end_layout
\begin_layout Plain Layout
def restId (e : Expense) =
\end_layout
\begin_layout Plain Layout
"http://www.pocketchangeapp.com/api/expense/" + e.id
\end_layout
\begin_layout Plain Layout
\end_layout
\begin_layout Plain Layout
// A simple helper to generate the REST timestamp of an Expense
\end_layout
\begin_layout Plain Layout
def restTimestamp (e : Expense) : String =
\end_layout
\begin_layout Plain Layout
timestamp.format(e.dateOf.is)
\end_layout
\end_inset
\end_layout
\begin_layout Standard
Listing
\begin_inset CommandInset ref
LatexCommand ref
reference "lst:Expense-Entity-JSON"
\end_inset
shows a helper method for generating a proper JSON representation of a
given
\family typewriter
Expense
\family default
using the Lift JSON DSL.
Although
\family typewriter
Expense
\family default
is a
\family typewriter
Mapper
\family default
entity, we don't use the
\family typewriter
Expense.asJs
\begin_inset Index
status open
\begin_layout Plain Layout
Mapper ! asJs
\end_layout
\end_inset
\family default
method inherited from
\family typewriter
Mapper
\family default
because we want to better control the format.
\end_layout
\begin_layout Standard
\begin_inset listings
inline false
status open
\begin_layout Plain Layout
\begin_inset Caption
\begin_layout Plain Layout
Expense Entity JSON Formatters
\begin_inset CommandInset label
LatexCommand label
name "lst:Expense-Entity-JSON"
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Plain Layout
/**
\end_layout
\begin_layout Plain Layout
* Generates the JSON REST representation of an Expense
\end_layout
\begin_layout Plain Layout
*/
\end_layout
\begin_layout Plain Layout
def toJSON (e : Expense) : JValue = {
\end_layout
\begin_layout Plain Layout
import net.liftweb.json.JsonDSL._
\end_layout
\begin_layout Plain Layout
import net.liftweb.json.JsonAST._
\end_layout
\begin_layout Plain Layout
\end_layout
\begin_layout Plain Layout
("expense" ->
\end_layout
\begin_layout Plain Layout
("id" -> restId(e)) ~
\end_layout