aboutsummaryrefslogtreecommitdiffstats
path: root/doc/src/manual/cowboy_rest.asciidoc
blob: fcef79970555e3cb4514907b25debfb10bddc370 (plain) (blame)
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
= cowboy_rest(3)

== Name

cowboy_rest - REST handlers

== Description

The module `cowboy_rest` implements the HTTP state machine.

Implementing REST handlers is not enough to provide a REST
interface; this interface must also follow the REST
constraints including HATEOAS (hypermedia as the engine
of application state).

== Callbacks

REST handlers implement the following interface:

[source,erlang]
----
init(Req, State)
    -> {cowboy_rest, Req, State}

Callback(Req, State)
    -> {Result, Req, State}
     | {stop, Req, State}
     | {{switch_handler, Module}, Req, State}
     | {{switch_handler, Module, Opts}, Req, State}

terminate(Reason, Req, State) -> ok  %% optional

Req    :: cowboy_req:req()
State  :: any()
Module :: module()
Opts   :: any()
Reason :: normal
        | {crash, error | exit | throw, any()}

Callback - see below
Result   - see below
Default  - see below
----

The `init/2` callback is common to all handlers. To switch
to the REST handler behavior, it must return `cowboy_rest`
as the first element of the tuple.

The `Callback/2` above represents all the REST-specific
callbacks. They are described in the following section
of this manual. REST-specific callbacks differ by their
name, semantics, result and default values. The default
value is the one used when the callback has not been
implemented. They otherwise all follow the same interface.

The `stop` tuple can be returned to stop REST processing.
If no response was sent before then, Cowboy will send a
'204 No Content'. The `stop` tuple can be returned from
any callback, excluding `expires`, `generate_etag`,
`last_modified` and `variances`.

A `switch_handler` tuple can be returned from these same
callbacks to stop REST processing and switch to a different
handler type. This is very useful to, for example, to stream
the response body.

The optional `terminate/3` callback will ultimately be called
with the reason for the termination of the handler.
Cowboy will terminate the process right after this. There
is no need to perform any cleanup in this callback.

The following terminate reasons are defined for loop handlers:

normal::
    The handler terminated normally.

{crash, Class, Reason}::
    A crash occurred in the handler. `Class` and `Reason` can be
    used to obtain more information about the crash.

== REST callbacks

=== AcceptCallback

[source,erlang]
----
AcceptCallback(Req, State) -> {Result, Req, State}

Result  :: true
         | {created, URI :: iodata()}
         | {see_other, URI :: iodata()}
         | false
Default  - crash
----

Process the request body.

This function should create or update the resource using the
request body.

For PUT requests, the body is a representation of the resource
that is being created or replaced.

For POST requests, the body is typically application-specific
instructions on how to process the request, but it may also be a
representation of the resource. When creating a new resource with POST
at a different location, return `{created, URI}` or `{see_other, URI}`
with `URI` the new location.

The `see_other` tuple will redirect the client to the new location
automatically.

For PATCH requests, the body is a series of instructions on
how to update the resource. Patch files or JSON Patch are
examples of such media types.

A response body may be sent. The appropriate media type, charset
and language for the response can be retrieved from the Req
object using the `media_type`, `charset` and `language` keys,
respectively. The body can be set using
link:man:cowboy_req:set_resp_body(3)[cowboy_req:set_resp_body(3)].

=== allowed_methods

[source,erlang]
----
allowed_methods(Req, State) -> {Result, Req, State}

Result  :: [binary()]  %% case sensitive
Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]
----

Return the list of allowed methods.

=== allow_missing_post

[source,erlang]
----
allow_missing_post(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: true
----

Return whether POST is allowed when the resource doesn't exist.

Returning `true` here means that a new resource will be
created. The URI for the newly created resource should be
returned from the `AcceptCallback` function.

=== charsets_provided

[source,erlang]
----
charsets_provided(Req, State) -> {Result, Req, State}

Result  :: [binary()]  %% lowercase; case insensitive
Default  - skip this step
----

Return the list of charsets the resource provides in order
of preference.

During content negotiation Cowboy will pick the most
appropriate charset for the client. The client advertises
charsets it prefers with the accept-charset header. When
that header is missing, Cowboy picks the first charset
from the resource.

// @todo We should explain precisely how charsets are picked.

Cowboy will add the negotiated `charset` to the Req object
after this step completes:

[source,erlang]
----
req() :: #{
    charset => binary()  %% lowercase; case insensitive
}
----

Note that Cowboy will only append the charset to the
content-type header of the response if the media type is text.

=== content_types_accepted

[source,erlang]
----
content_types_accepted(Req, State) -> {Result, Req, State}

Result     :: [{'*' | binary() | ParsedMime, AcceptCallback :: atom()}]
ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
Params     :: [{Key :: binary(), Value :: binary()}]

Default     - crash
----

// @todo Case sensitivity of parsed mime content?

Return the list of media types the resource accepts in
order of preference.

A media type is made of different parts. The media type
`text/html;charset=utf-8` is of type `text`, subtype `html`
and has a single parameter `charset` with value `utf-8`.

The special value `'*'` can be used to accept any media type.

// @todo Cowboy needs to ignore the boundary parameter for
// multipart, as we never want to match against it. Or allow
// ignoring specific parameters at the very least.

Cowboy will match the content-type request header against
the media types the server accepts and select the appropriate
callback. When that header is missing, or when the server does not
accept this media type, the request fails and an error response
is returned. Cowboy will execute the callback immediately otherwise.

// @todo We should explain precisely how media types are picked.

An empty parameters list `[]` means that no parameters will be
accepted. When any parameter is acceptable, the tuple form
should be used with parameters as the atom `'*'`.

Cowboy treats all parameters as case sensitive, except for the
`charset` parameter, which is known to be case insensitive. You
should therefore always provide the charset as a lowercase
binary string.

// @todo Maybe this should be in the user guide instead.
//This function will be called for POST, PUT and PATCH requests.
//It is entirely possible to define different callbacks for different
//methods if the handling of the request differs. Simply verify
//what the method is with `cowboy_req:method/1` and return a
//different list for each methods.

=== content_types_provided

[source,erlang]
----
content_types_provided(Req, State) -> {Result, Req, State}

Result     :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
Params     :: [{Key :: binary(), Value :: binary()}]

Default     - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
----

// @todo Case sensitivity of parsed mime content?
// @todo Space required for the time being: https://github.com/spf13/hugo/issues/2398

Return the list of media types the resource provides in
order of preference.

A media type is made of different parts. The media type
`text/html;charset=utf-8` is of type `text`, subtype `html`
and has a single parameter `charset` with value `utf-8`.

// @todo Cowboy needs to ignore the boundary parameter for
// multipart, as we never want to match against it. Or allow
// ignoring specific parameters at the very least.

During content negotiation Cowboy will pick the most appropriate
media type for the client. The client advertises media types it
prefers with the accept header. When that header is missing,
the content negotiation fails and an error response is returned.

The callback given for the selected media type will be called
at the end of the execution of GET and HEAD requests when a
representation must be sent to the client.

// @todo We should explain precisely how media types are picked.

An empty parameters list `[]` means that no parameters will be
accepted. When any parameter is acceptable, the tuple form
should be used with parameters as the atom `'*'`.

Cowboy treats all parameters as case sensitive, except for the
`charset` parameter, which is known to be case insensitive. You
should therefore always provide the charset as a lowercase
binary string.

When a charset is given in the media type parameters in the
accept header, Cowboy will do some additional checks to confirm
that it can use this charset. When the wildcard is used then Cowboy
will immediately call `charsets_provided` to confirm the charset
is acceptable. If the callback is undefined Cowboy assumes any
charset is acceptable. When the wildcard is not used and the charset
given in the accept header matches one of the configured media
types Cowboy will use that charset and skip the `charsets_provided`
step entirely.

Cowboy will add the negotiated `media_type` to the Req object
after this step completes:

[source,erlang]
----
req() :: #{
    media_type => ParsedMime
}
----

// @todo Case sensitivity of parsed mime content?

Cowboy may also add the negotiated `charset` to the Req object
after this step completes:

[source,erlang]
----
req() :: #{
    charset => binary()  %% lowercase; case insensitive
}
----

=== delete_completed

[source,erlang]
----
delete_completed(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: true
----

Return whether the resource has been fully deleted from the
system, including from any internal cache.

Returning `false` will result in a '202 Accepted' response
being sent instead of a '200 OK' or '204 No Content'.

=== delete_resource

[source,erlang]
----
delete_resource(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: false
----

Delete the resource.

Cowboy will send an error response when this function
returns `false`.

=== expires

[source,erlang]
----
expires(Req, State) -> {Result, Req, State}

Result  :: calendar:datetime() | binary() | undefined
Default :: undefined
----

Return the resource's expiration date.

=== forbidden

[source,erlang]
----
forbidden(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: false
----

Return whether access to the resource is forbidden.

A '403 Forbidden' response will be sent if this
function returns `true`. This status code means that
access is forbidden regardless of authentication,
and that the request shouldn't be repeated.

=== generate_etag

[source,erlang]
----
generate_etag(Req, State) -> {Result, Req, State}

Result  :: binary() | {weak | strong, binary()} | undefined
Default  - no etag value
----

Return the entity tag of the resource.

When a binary is returned, the value is automatically
parsed to a tuple. The binary must be in the same
format as the etag header, including quotes.

It is possible to conditionally generate an etag.
When no etag can be generated, `undefined` should
be returned.

=== is_authorized

[source,erlang]
----
is_authorized(Req, State) -> {Result, Req, State}

Result  :: true | {false, AuthHeader :: iodata()}
Default  - true
----

Return whether the user is authorized to perform the action.

This function should be used to perform any necessary
authentication of the user before attempting to perform
any action on the resource.

When authentication fails, the `AuthHeader` value will
be sent in the www-authenticate header for the
'401 Unauthorized' response.

=== is_conflict

[source,erlang]
----
is_conflict(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: false
----

Return whether the PUT request results in a conflict.

A '409 Conflict' response is sent when `true`.

=== known_methods

[source,erlang]
----
known_methods(Req, State) -> {Result, Req, State}

Result  :: [binary()]  %% case sensitive
Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>,
            <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
----

Return the list of known methods.

The full list of methods known by the server should be
returned, regardless of their use in the resource.

The default value lists the methods Cowboy knows and
implement in `cowboy_rest`.

=== languages_provided

[source,erlang]
----
languages_provided(Req, State) -> {Result, Req, State}

Result  :: [binary()]  %% lowercase; case insensitive
Default  - skip this step
----

Return the list of languages the resource provides in order
of preference.

During content negotiation Cowboy will pick the most
appropriate language for the client. The client advertises
languages it prefers with the accept-language header. When
that header is missing, Cowboy picks the first language
from the resource.

// @todo We should explain precisely how languages are picked.

Cowboy will add the negotiated `language` to the Req object
after this step completes:

[source,erlang]
----
req() :: #{
    language => binary()  %% lowercase; case insensitive
}
----

=== last_modified

[source,erlang]
----
last_modified(Req, State) -> {Result, Req, State}

Result  :: calendar:datetime()
Default  - no last modified value
----

Return the resource's last modification date.

This date will be used to test against the if-modified-since
and if-unmodified-since headers, and sent as the last-modified
header in the response to GET and HEAD requests.

=== malformed_request

[source,erlang]
----
malformed_request(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: false
----

Return whether the request is malformed.

A request is malformed when a component required by the
resource is invalid. This may include the query string
or individual headers. They should be parsed and validated
in this function. The body should not be read at this point.

=== moved_permanently

[source,erlang]
----
moved_permanently(Req, State) -> {Result, Req, State}

Result  :: {true, URI :: iodata()} | false
Default :: false
----

Return whether the resource was permanently moved, and
what its new location is.

=== moved_temporarily

[source,erlang]
----
moved_temporarily(Req, State) -> {Result, Req, State}

Result  :: {true, URI :: iodata()} | false
Default :: false
----

Return whether the resource was temporarily moved, and
what its new location is.

=== multiple_choices

[source,erlang]
----
multiple_choices(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: false
----

Return whether the client should engage in reactive
negotiation.

Return `true` when the server has multiple representations
of a resource, each with their specific identifier, but is
unable to determine which is best for the client. For
example an image might have different sizes and the server
is unable to determine the capabilities of the client.

When returning `true` the server should send a body with
links to the different representations. If the server has
a preferred representation it can send its link inside a
location header.

Note that when replying manually in this callback you
should either call `cowboy_req:reply/4` or remove the
response body that Cowboy sets to avoid surprises.

=== options

[source,erlang]
----
options(Req, State) -> {ok, Req, State}
----

Respond to an OPTIONS request.

The response should inform the client the communication
options available for this resource. By default Cowboy
will send a '200 OK' response with the allow header set.

=== previously_existed

[source,erlang]
----
previously_existed(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: false
----

Return whether the resource existed previously.

=== ProvideCallback

[source,erlang]
----
ProvideCallback(Req, State) -> {Result, Req, State}

Result  :: cowboy_req:resp_body()
Default  - crash
----

Return the response body.

The response body can be provided either as the actual data
to be sent or a tuple indicating which file to send.

This function is called for both GET and HEAD requests. For
the latter the body is not sent: it is only used to calculate
the content length.

// @todo Perhaps we can optimize HEAD requests and just
// allow calculating the length instead of returning the
// whole thing.

It is possible to stream the response body either by manually
sending the response and returning a `stop` value; or by
switching to a different handler (for example a loop handler)
and manually sending the response. All headers already set
by Cowboy will also be included in the response.

== RangeCallback

[source,erlang]
----
RangeCallback(Req, State) -> {Result, Req, State}

Result  :: [{Range, Body}]
Range   :: {From, To, Total} | binary()
From    :: non_neg_integer()
To      :: non_neg_integer()
Total   :: non_neg_integer() | '*'
Body    :: cowboy_req:resp_body()
Default  - crash
----

Return a list of ranges for the response body.

The range selected can be found in the key `range`
in the Req object, as indicated in `range_satisfiable`.

Instead of returning the full response body as would
be done in the `ProvideCallback`, a list of ranges
must be returned. There can be one or more range.
When one range is returned, a normal ranged response
is sent. When multiple ranges are returned, Cowboy
will automatically send a multipart/byteranges
response.

When the total is not known the atom `'*'` can be
returned.

== ranges_provided

[source,erlang]
----
ranges_provided(Req, State) -> {Result, Req, State}

Result :: [Range | Auto]
Range  :: {
    binary(),  %% lowercase; case insensitive
    RangeCallback :: atom()
}
Auto   :: {<<"bytes">>, auto}
Default - skip this step
----

Return the list of range units the resource provides.

During content negotiation Cowboy will build an accept-ranges
response header with the list of ranges provided. Cowboy
does not choose a range at this time; ranges are choosen
when it comes time to call the `ProvideCallback`.

By default ranged requests will be handled the same as normal
requests: the `ProvideCallback` will be called and the full
response body will be sent.

It is possible to let Cowboy handle ranged responses
automatically when the range unit is bytes and the
atom returned is `auto` (instead of a callback name).
In that case Cowboy will call the `ProvideCallback`
and split the response automatically, including by
producing a multipart/byteranges response if necessary.

== range_satisfiable

[source,erlang]
----
range_satisfiable(Req, State) -> {Result, Req, State}

Result  :: boolean() | {false, non_neg_integer() | iodata()}
Default :: true
----

Whether the range request is satisfiable.

When the time comes to send the response body, and when
ranges have been provided via the `ranges_provided`
callback, Cowboy will process the if-range and the
range request headers and ensure it is satisfiable.

This callback allows making resource-specific checks
before sending the ranged response. The default is
to accept sending a ranged response.

Cowboy adds the requested `range` to the Req object
just before calling this callback:

[source,erlang]
----
req() :: #{
    range => {
        binary(),  %% lowercase; case insensitive
        Range
    }
}

Range     :: ByteRange | binary()

ByteRange :: [{FirstByte, LastByte | infinity} | SuffixLen]
FirstByte :: non_neg_integer()
LastByte  :: non_neg_integer()
SuffixLen :: neg_integer()
----

Only byte ranges are parsed. Other ranges are provided
as binary. Byte ranges may either be requested from first
to last bytes (inclusive); from first bytes to the end
(`infinity` is used to represent the last byte); or
the last bytes of the representation via a negative
integer (so -500 means the last 500 bytes).

Returning `false` will result in a 416 Range Not Satisfiable
response being sent. The content-range header will be
set automatically in the response if a tuple is
returned. The integer value represents the total
size (in the choosen unit) of the resource. An
iodata value may also be returned and will be
used as-is to build the content range header,
prepended with the unit choosen.

=== rate_limited

[source,erlang]
----
rate_limited(Req, State) -> {Result, Req, State}

Result     :: false | {true, RetryAfter}
RetryAfter :: non_neg_integer() | calendar:datetime()
Default    :: false
----

Return whether the user is rate limited.

This function can be used to temporarily restrict
access to a resource when the user has issued too
many requests.

When the resource is rate limited the `RetryAfter`
value will be sent in the retry-after header for the
'429 Too Many Requests' response. It indicates when
the resource will become available again and can be
specified as a number of seconds in the future or a
specific date/time.

=== resource_exists

[source,erlang]
----
resource_exists(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: true
----

Return whether the resource exists.

=== service_available

[source,erlang]
----
service_available(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: true
----

Return whether the service is available.

A '503 Service Unavailable' response will be sent when this
function returns `false`.

=== uri_too_long

[source,erlang]
----
uri_too_long(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: false
----

Return whether the requested URI is too long.

This function can be used to further restrict the length
of the URI for this specific resource.

=== valid_content_headers

[source,erlang]
----
valid_content_headers(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: true
----

Return whether the content headers are valid.

This callback can be used to reject requests that have
invalid content header values, for example an unsupported
content-encoding.

=== valid_entity_length

[source,erlang]
----
valid_entity_length(Req, State) -> {Result, Req, State}

Result  :: boolean()
Default :: true
----

Return whether the request body length is within acceptable boundaries.

A '413 Request Entity Too Large' response will be sent if this
function returns `false`.

=== variances

[source,erlang]
----
variances(Req, State) -> {Result, Req, State}

Result  :: [binary()]  %% case insensitive
Default :: []
----

Return the list of request headers that affect the
representation of the resource.

Cowboy automatically adds the accept, accept-charset and
accept-language headers when necessary. It's also useful
to note that some standard headers also do not need to be
listed here, like the authorization header.

== Changelog

* *2.11*: The `ranges_provided`, `range_satisfiable` and
          the `RangeCallback` callbacks have been added.
* *2.11*: The `generate_etag` callback can now return
          `undefined` to conditionally avoid generating
          an etag.
* *2.9*: An `AcceptCallback` can now return `{created, URI}` or
         `{see_other, URI}`. The return value `{true, URI}`
         is deprecated.
* *2.7*: The media type wildcard in `content_types_accepted`
         is now documented.
* *2.6*: The callback `rate_limited` was added.
* *2.1*: The `switch_handler` return value was added.
* *1.0*: Behavior introduced.

== See also

link:man:cowboy(7)[cowboy(7)],
link:man:cowboy_handler(3)[cowboy_handler(3)]