Debian Codegraph @

doc/src/manual/cowboy_rest.asciidoc

raw
1 = cowboy_rest(3)
2
3 == Name
4
5 cowboy_rest - REST handlers
6
7 == Description
8
9 The module `cowboy_rest` implements the HTTP state machine.
10
11 Implementing REST handlers is not enough to provide a REST
12 interface; this interface must also follow the REST
13 constraints including HATEOAS (hypermedia as the engine
14 of application state).
15
16 == Callbacks
17
18 REST handlers implement the following interface:
19
20 [source,erlang]
21 ----
22 init(Req, State)
23 -> {cowboy_rest, Req, State}
24
25 Callback(Req, State)
26 -> {Result, Req, State}
27 | {stop, Req, State}
28 | {{switch_handler, Module}, Req, State}
29 | {{switch_handler, Module, Opts}, Req, State}
30
31 terminate(Reason, Req, State) -> ok %% optional
32
33 Req :: cowboy_req:req()
34 State :: any()
35 Module :: module()
36 Opts :: any()
37 Reason :: normal
38 | {crash, error | exit | throw, any()}
39
40 Callback - see below
41 Result - see below
42 Default - see below
43 ----
44
45 The `init/2` callback is common to all handlers. To switch
46 to the REST handler behavior, it must return `cowboy_rest`
47 as the first element of the tuple.
48
49 The `Callback/2` above represents all the REST-specific
50 callbacks. They are described in the following section
51 of this manual. REST-specific callbacks differ by their
52 name, semantics, result and default values. The default
53 value is the one used when the callback has not been
54 implemented. They otherwise all follow the same interface.
55
56 The `stop` tuple can be returned to stop REST processing.
57 If no response was sent before then, Cowboy will send a
58 '204 No Content'. The `stop` tuple can be returned from
59 any callback, excluding `expires`, `generate_etag`,
60 `last_modified` and `variances`.
61
62 A `switch_handler` tuple can be returned from these same
63 callbacks to stop REST processing and switch to a different
64 handler type. This is very useful to, for example, to stream
65 the response body.
66
67 The optional `terminate/3` callback will ultimately be called
68 with the reason for the termination of the handler.
69 Cowboy will terminate the process right after this. There
70 is no need to perform any cleanup in this callback.
71
72 The following terminate reasons are defined for loop handlers:
73
74 normal::
75 The handler terminated normally.
76
77 {crash, Class, Reason}::
78 A crash occurred in the handler. `Class` and `Reason` can be
79 used to obtain more information about the crash.
80
81 == REST callbacks
82
83 === AcceptCallback
84
85 [source,erlang]
86 ----
87 AcceptCallback(Req, State) -> {Result, Req, State}
88
89 Result :: true
90 | {created, URI :: iodata()}
91 | {see_other, URI :: iodata()}
92 | false
93 Default - crash
94 ----
95
96 Process the request body.
97
98 This function should create or update the resource using the
99 request body.
100
101 For PUT requests, the body is a representation of the resource
102 that is being created or replaced.
103
104 For POST requests, the body is typically application-specific
105 instructions on how to process the request, but it may also be a
106 representation of the resource. When creating a new resource with POST
107 at a different location, return `{created, URI}` or `{see_other, URI}`
108 with `URI` the new location.
109
110 The `see_other` tuple will redirect the client to the new location
111 automatically.
112
113 For PATCH requests, the body is a series of instructions on
114 how to update the resource. Patch files or JSON Patch are
115 examples of such media types.
116
117 A response body may be sent. The appropriate media type, charset
118 and language for the response can be retrieved from the Req
119 object using the `media_type`, `charset` and `language` keys,
120 respectively. The body can be set using
121 link:man:cowboy_req:set_resp_body(3)[cowboy_req:set_resp_body(3)].
122
123 === allowed_methods
124
125 [source,erlang]
126 ----
127 allowed_methods(Req, State) -> {Result, Req, State}
128
129 Result :: [binary()] %% case sensitive
130 Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]
131 ----
132
133 Return the list of allowed methods.
134
135 === allow_missing_post
136
137 [source,erlang]
138 ----
139 allow_missing_post(Req, State) -> {Result, Req, State}
140
141 Result :: boolean()
142 Default :: true
143 ----
144
145 Return whether POST is allowed when the resource doesn't exist.
146
147 Returning `true` here means that a new resource will be
148 created. The URI for the newly created resource should be
149 returned from the `AcceptCallback` function.
150
151 === charsets_provided
152
153 [source,erlang]
154 ----
155 charsets_provided(Req, State) -> {Result, Req, State}
156
157 Result :: [binary()] %% lowercase; case insensitive
158 Default - skip this step
159 ----
160
161 Return the list of charsets the resource provides in order
162 of preference.
163
164 During content negotiation Cowboy will pick the most
165 appropriate charset for the client. The client advertises
166 charsets it prefers with the accept-charset header. When
167 that header is missing, Cowboy picks the first charset
168 from the resource.
169
170 // @todo We should explain precisely how charsets are picked.
171
172 Cowboy will add the negotiated `charset` to the Req object
173 after this step completes:
174
175 [source,erlang]
176 ----
177 req() :: #{
178 charset => binary() %% lowercase; case insensitive
179 }
180 ----
181
182 Note that Cowboy will only append the charset to the
183 content-type header of the response if the media type is text.
184
185 === content_types_accepted
186
187 [source,erlang]
188 ----
189 content_types_accepted(Req, State) -> {Result, Req, State}
190
191 Result :: [{'*' | binary() | ParsedMime, AcceptCallback :: atom()}]
192 ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
193 Params :: [{Key :: binary(), Value :: binary()}]
194
195 Default - crash
196 ----
197
198 // @todo Case sensitivity of parsed mime content?
199
200 Return the list of media types the resource accepts in
201 order of preference.
202
203 A media type is made of different parts. The media type
204 `text/html;charset=utf-8` is of type `text`, subtype `html`
205 and has a single parameter `charset` with value `utf-8`.
206
207 The special value `'*'` can be used to accept any media type.
208
209 // @todo Cowboy needs to ignore the boundary parameter for
210 // multipart, as we never want to match against it. Or allow
211 // ignoring specific parameters at the very least.
212
213 Cowboy will match the content-type request header against
214 the media types the server accepts and select the appropriate
215 callback. When that header is missing, or when the server does not
216 accept this media type, the request fails and an error response
217 is returned. Cowboy will execute the callback immediately otherwise.
218
219 // @todo We should explain precisely how media types are picked.
220
221 An empty parameters list `[]` means that no parameters will be
222 accepted. When any parameter is acceptable, the tuple form
223 should be used with parameters as the atom `'*'`.
224
225 Cowboy treats all parameters as case sensitive, except for the
226 `charset` parameter, which is known to be case insensitive. You
227 should therefore always provide the charset as a lowercase
228 binary string.
229
230 // @todo Maybe this should be in the user guide instead.
231 //This function will be called for POST, PUT and PATCH requests.
232 //It is entirely possible to define different callbacks for different
233 //methods if the handling of the request differs. Simply verify
234 //what the method is with `cowboy_req:method/1` and return a
235 //different list for each methods.
236
237 === content_types_provided
238
239 [source,erlang]
240 ----
241 content_types_provided(Req, State) -> {Result, Req, State}
242
243 Result :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
244 ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
245 Params :: [{Key :: binary(), Value :: binary()}]
246
247 Default - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
248 ----
249
250 // @todo Case sensitivity of parsed mime content?
251 // @todo Space required for the time being: https://github.com/spf13/hugo/issues/2398
252
253 Return the list of media types the resource provides in
254 order of preference.
255
256 A media type is made of different parts. The media type
257 `text/html;charset=utf-8` is of type `text`, subtype `html`
258 and has a single parameter `charset` with value `utf-8`.
259
260 // @todo Cowboy needs to ignore the boundary parameter for
261 // multipart, as we never want to match against it. Or allow
262 // ignoring specific parameters at the very least.
263
264 During content negotiation Cowboy will pick the most appropriate
265 media type for the client. The client advertises media types it
266 prefers with the accept header. When that header is missing,
267 the content negotiation fails and an error response is returned.
268
269 The callback given for the selected media type will be called
270 at the end of the execution of GET and HEAD requests when a
271 representation must be sent to the client.
272
273 // @todo We should explain precisely how media types are picked.
274
275 An empty parameters list `[]` means that no parameters will be
276 accepted. When any parameter is acceptable, the tuple form
277 should be used with parameters as the atom `'*'`.
278
279 Cowboy treats all parameters as case sensitive, except for the
280 `charset` parameter, which is known to be case insensitive. You
281 should therefore always provide the charset as a lowercase
282 binary string.
283
284 When a charset is given in the media type parameters in the
285 accept header, Cowboy will do some additional checks to confirm
286 that it can use this charset. When the wildcard is used then Cowboy
287 will immediately call `charsets_provided` to confirm the charset
288 is acceptable. If the callback is undefined Cowboy assumes any
289 charset is acceptable. When the wildcard is not used and the charset
290 given in the accept header matches one of the configured media
291 types Cowboy will use that charset and skip the `charsets_provided`
292 step entirely.
293
294 Cowboy will add the negotiated `media_type` to the Req object
295 after this step completes:
296
297 [source,erlang]
298 ----
299 req() :: #{
300 media_type => ParsedMime
301 }
302 ----
303
304 // @todo Case sensitivity of parsed mime content?
305
306 Cowboy may also add the negotiated `charset` to the Req object
307 after this step completes:
308
309 [source,erlang]
310 ----
311 req() :: #{
312 charset => binary() %% lowercase; case insensitive
313 }
314 ----
315
316 === delete_completed
317
318 [source,erlang]
319 ----
320 delete_completed(Req, State) -> {Result, Req, State}
321
322 Result :: boolean()
323 Default :: true
324 ----
325
326 Return whether the resource has been fully deleted from the
327 system, including from any internal cache.
328
329 Returning `false` will result in a '202 Accepted' response
330 being sent instead of a '200 OK' or '204 No Content'.
331
332 === delete_resource
333
334 [source,erlang]
335 ----
336 delete_resource(Req, State) -> {Result, Req, State}
337
338 Result :: boolean()
339 Default :: false
340 ----
341
342 Delete the resource.
343
344 Cowboy will send an error response when this function
345 returns `false`.
346
347 === expires
348
349 [source,erlang]
350 ----
351 expires(Req, State) -> {Result, Req, State}
352
353 Result :: calendar:datetime() | binary() | undefined
354 Default :: undefined
355 ----
356
357 Return the resource's expiration date.
358
359 === forbidden
360
361 [source,erlang]
362 ----
363 forbidden(Req, State) -> {Result, Req, State}
364
365 Result :: boolean()
366 Default :: false
367 ----
368
369 Return whether access to the resource is forbidden.
370
371 A '403 Forbidden' response will be sent if this
372 function returns `true`. This status code means that
373 access is forbidden regardless of authentication,
374 and that the request shouldn't be repeated.
375
376 === generate_etag
377
378 [source,erlang]
379 ----
380 generate_etag(Req, State) -> {Result, Req, State}
381
382 Result :: binary() | {weak | strong, binary()} | undefined
383 Default - no etag value
384 ----
385
386 Return the entity tag of the resource.
387
388 When a binary is returned, the value is automatically
389 parsed to a tuple. The binary must be in the same
390 format as the etag header, including quotes.
391
392 It is possible to conditionally generate an etag.
393 When no etag can be generated, `undefined` should
394 be returned.
395
396 === is_authorized
397
398 [source,erlang]
399 ----
400 is_authorized(Req, State) -> {Result, Req, State}
401
402 Result :: true | {false, AuthHeader :: iodata()}
403 Default - true
404 ----
405
406 Return whether the user is authorized to perform the action.
407
408 This function should be used to perform any necessary
409 authentication of the user before attempting to perform
410 any action on the resource.
411
412 When authentication fails, the `AuthHeader` value will
413 be sent in the www-authenticate header for the
414 '401 Unauthorized' response.
415
416 === is_conflict
417
418 [source,erlang]
419 ----
420 is_conflict(Req, State) -> {Result, Req, State}
421
422 Result :: boolean()
423 Default :: false
424 ----
425
426 Return whether the PUT request results in a conflict.
427
428 A '409 Conflict' response is sent when `true`.
429
430 === known_methods
431
432 [source,erlang]
433 ----
434 known_methods(Req, State) -> {Result, Req, State}
435
436 Result :: [binary()] %% case sensitive
437 Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>,
438 <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
439 ----
440
441 Return the list of known methods.
442
443 The full list of methods known by the server should be
444 returned, regardless of their use in the resource.
445
446 The default value lists the methods Cowboy knows and
447 implement in `cowboy_rest`.
448
449 === languages_provided
450
451 [source,erlang]
452 ----
453 languages_provided(Req, State) -> {Result, Req, State}
454
455 Result :: [binary()] %% lowercase; case insensitive
456 Default - skip this step
457 ----
458
459 Return the list of languages the resource provides in order
460 of preference.
461
462 During content negotiation Cowboy will pick the most
463 appropriate language for the client. The client advertises
464 languages it prefers with the accept-language header. When
465 that header is missing, Cowboy picks the first language
466 from the resource.
467
468 // @todo We should explain precisely how languages are picked.
469
470 Cowboy will add the negotiated `language` to the Req object
471 after this step completes:
472
473 [source,erlang]
474 ----
475 req() :: #{
476 language => binary() %% lowercase; case insensitive
477 }
478 ----
479
480 === last_modified
481
482 [source,erlang]
483 ----
484 last_modified(Req, State) -> {Result, Req, State}
485
486 Result :: calendar:datetime() | undefined
487 Default - no last modified value
488 ----
489
490 Return the resource's last modification date.
491
492 This date will be used to test against the if-modified-since
493 and if-unmodified-since headers, and sent as the last-modified
494 header in the response to GET and HEAD requests.
495
496 When `undefined` is returned, no last-modified header is
497 added to response. Can be useful if you save timestamp on store
498 action in memory and lose it after restart.
499
500 === malformed_request
501
502 [source,erlang]
503 ----
504 malformed_request(Req, State) -> {Result, Req, State}
505
506 Result :: boolean()
507 Default :: false
508 ----
509
510 Return whether the request is malformed.
511
512 A request is malformed when a component required by the
513 resource is invalid. This may include the query string
514 or individual headers. They should be parsed and validated
515 in this function. The body should not be read at this point.
516
517 === moved_permanently
518
519 [source,erlang]
520 ----
521 moved_permanently(Req, State) -> {Result, Req, State}
522
523 Result :: {true, URI :: iodata()} | false
524 Default :: false
525 ----
526
527 Return whether the resource was permanently moved, and
528 what its new location is.
529
530 === moved_temporarily
531
532 [source,erlang]
533 ----
534 moved_temporarily(Req, State) -> {Result, Req, State}
535
536 Result :: {true, URI :: iodata()} | false
537 Default :: false
538 ----
539
540 Return whether the resource was temporarily moved, and
541 what its new location is.
542
543 === multiple_choices
544
545 [source,erlang]
546 ----
547 multiple_choices(Req, State) -> {Result, Req, State}
548
549 Result :: boolean()
550 Default :: false
551 ----
552
553 Return whether the client should engage in reactive
554 negotiation.
555
556 Return `true` when the server has multiple representations
557 of a resource, each with their specific identifier, but is
558 unable to determine which is best for the client. For
559 example an image might have different sizes and the server
560 is unable to determine the capabilities of the client.
561
562 When returning `true` the server should send a body with
563 links to the different representations. If the server has
564 a preferred representation it can send its link inside a
565 location header.
566
567 Note that when replying manually in this callback you
568 should either call `cowboy_req:reply/4` or remove the
569 response body that Cowboy sets to avoid surprises.
570
571 === options
572
573 [source,erlang]
574 ----
575 options(Req, State) -> {ok, Req, State}
576 ----
577
578 Respond to an OPTIONS request.
579
580 The response should inform the client the communication
581 options available for this resource. By default Cowboy
582 will send a '200 OK' response with the allow header set.
583
584 === previously_existed
585
586 [source,erlang]
587 ----
588 previously_existed(Req, State) -> {Result, Req, State}
589
590 Result :: boolean()
591 Default :: false
592 ----
593
594 Return whether the resource existed previously.
595
596 === ProvideCallback
597
598 [source,erlang]
599 ----
600 ProvideCallback(Req, State) -> {Result, Req, State}
601
602 Result :: cowboy_req:resp_body()
603 Default - crash
604 ----
605
606 Return the response body.
607
608 The response body can be provided either as the actual data
609 to be sent or a tuple indicating which file to send.
610
611 This function is called for both GET and HEAD requests. For
612 the latter the body is not sent: it is only used to calculate
613 the content length.
614
615 // @todo Perhaps we can optimize HEAD requests and just
616 // allow calculating the length instead of returning the
617 // whole thing.
618
619 It is possible to stream the response body either by manually
620 sending the response and returning a `stop` value; or by
621 switching to a different handler (for example a loop handler)
622 and manually sending the response. All headers already set
623 by Cowboy will also be included in the response.
624
625 == RangeCallback
626
627 [source,erlang]
628 ----
629 RangeCallback(Req, State) -> {Result, Req, State}
630
631 Result :: [{Range, Body}]
632 Range :: {From, To, Total} | binary()
633 From :: non_neg_integer()
634 To :: non_neg_integer()
635 Total :: non_neg_integer() | '*'
636 Body :: cowboy_req:resp_body()
637 Default - crash
638 ----
639
640 Return a list of ranges for the response body.
641
642 The range selected can be found in the key `range`
643 in the Req object, as indicated in `range_satisfiable`.
644
645 Instead of returning the full response body as would
646 be done in the `ProvideCallback`, a list of ranges
647 must be returned. There can be one or more range.
648 When one range is returned, a normal ranged response
649 is sent. When multiple ranges are returned, Cowboy
650 will automatically send a multipart/byteranges
651 response.
652
653 When the total is not known the atom `'*'` can be
654 returned.
655
656 == ranges_provided
657
658 [source,erlang]
659 ----
660 ranges_provided(Req, State) -> {Result, Req, State}
661
662 Result :: [Range | Auto]
663 Range :: {
664 binary(), %% lowercase; case insensitive
665 RangeCallback :: atom()
666 }
667 Auto :: {<<"bytes">>, auto}
668 Default - skip this step
669 ----
670
671 Return the list of range units the resource provides.
672
673 During content negotiation Cowboy will build an accept-ranges
674 response header with the list of ranges provided. Cowboy
675 does not choose a range at this time; ranges are choosen
676 when it comes time to call the `ProvideCallback`.
677
678 By default ranged requests will be handled the same as normal
679 requests: the `ProvideCallback` will be called and the full
680 response body will be sent.
681
682 It is possible to let Cowboy handle ranged responses
683 automatically when the range unit is bytes and the
684 atom returned is `auto` (instead of a callback name).
685 In that case Cowboy will call the `ProvideCallback`
686 and split the response automatically, including by
687 producing a multipart/byteranges response if necessary.
688
689 == range_satisfiable
690
691 [source,erlang]
692 ----
693 range_satisfiable(Req, State) -> {Result, Req, State}
694
695 Result :: boolean() | {false, non_neg_integer() | iodata()}
696 Default :: true
697 ----
698
699 Whether the range request is satisfiable.
700
701 When the time comes to send the response body, and when
702 ranges have been provided via the `ranges_provided`
703 callback, Cowboy will process the if-range and the
704 range request headers and ensure it is satisfiable.
705
706 This callback allows making resource-specific checks
707 before sending the ranged response. The default is
708 to accept sending a ranged response.
709
710 Cowboy adds the requested `range` to the Req object
711 just before calling this callback:
712
713 [source,erlang]
714 ----
715 req() :: #{
716 range => {
717 binary(), %% lowercase; case insensitive
718 Range
719 }
720 }
721
722 Range :: ByteRange | binary()
723
724 ByteRange :: [{FirstByte, LastByte | infinity} | SuffixLen]
725 FirstByte :: non_neg_integer()
726 LastByte :: non_neg_integer()
727 SuffixLen :: neg_integer()
728 ----
729
730 Only byte ranges are parsed. Other ranges are provided
731 as binary. Byte ranges may either be requested from first
732 to last bytes (inclusive); from first bytes to the end
733 (`infinity` is used to represent the last byte); or
734 the last bytes of the representation via a negative
735 integer (so -500 means the last 500 bytes).
736
737 Returning `false` will result in a 416 Range Not Satisfiable
738 response being sent. The content-range header will be
739 set automatically in the response if a tuple is
740 returned. The integer value represents the total
741 size (in the choosen unit) of the resource. An
742 iodata value may also be returned and will be
743 used as-is to build the content range header,
744 prepended with the unit choosen.
745
746 === rate_limited
747
748 [source,erlang]
749 ----
750 rate_limited(Req, State) -> {Result, Req, State}
751
752 Result :: false | {true, RetryAfter}
753 RetryAfter :: non_neg_integer() | calendar:datetime()
754 Default :: false
755 ----
756
757 Return whether the user is rate limited.
758
759 This function can be used to temporarily restrict
760 access to a resource when the user has issued too
761 many requests.
762
763 When the resource is rate limited the `RetryAfter`
764 value will be sent in the retry-after header for the
765 '429 Too Many Requests' response. It indicates when
766 the resource will become available again and can be
767 specified as a number of seconds in the future or a
768 specific date/time.
769
770 === resource_exists
771
772 [source,erlang]
773 ----
774 resource_exists(Req, State) -> {Result, Req, State}
775
776 Result :: boolean()
777 Default :: true
778 ----
779
780 Return whether the resource exists.
781
782 === service_available
783
784 [source,erlang]
785 ----
786 service_available(Req, State) -> {Result, Req, State}
787
788 Result :: boolean()
789 Default :: true
790 ----
791
792 Return whether the service is available.
793
794 A '503 Service Unavailable' response will be sent when this
795 function returns `false`.
796
797 === uri_too_long
798
799 [source,erlang]
800 ----
801 uri_too_long(Req, State) -> {Result, Req, State}
802
803 Result :: boolean()
804 Default :: false
805 ----
806
807 Return whether the requested URI is too long.
808
809 This function can be used to further restrict the length
810 of the URI for this specific resource.
811
812 === valid_content_headers
813
814 [source,erlang]
815 ----
816 valid_content_headers(Req, State) -> {Result, Req, State}
817
818 Result :: boolean()
819 Default :: true
820 ----
821
822 Return whether the content headers are valid.
823
824 This callback can be used to reject requests that have
825 invalid content header values, for example an unsupported
826 content-encoding.
827
828 === valid_entity_length
829
830 [source,erlang]
831 ----
832 valid_entity_length(Req, State) -> {Result, Req, State}
833
834 Result :: boolean()
835 Default :: true
836 ----
837
838 Return whether the request body length is within acceptable boundaries.
839
840 A '413 Request Entity Too Large' response will be sent if this
841 function returns `false`.
842
843 === variances
844
845 [source,erlang]
846 ----
847 variances(Req, State) -> {Result, Req, State}
848
849 Result :: [binary()] %% case insensitive
850 Default :: []
851 ----
852
853 Return the list of request headers that affect the
854 representation of the resource.
855
856 Cowboy automatically adds the accept, accept-charset and
857 accept-language headers when necessary. It's also useful
858 to note that some standard headers also do not need to be
859 listed here, like the authorization header.
860
861 == Changelog
862
863 * *2.14*: The `last_modified` callback is now type correct
864 when returning `undefined` to avoid responding
865 a last-modified header.
866 * *2.11*: The `ranges_provided`, `range_satisfiable` and
867 the `RangeCallback` callbacks have been added.
868 * *2.11*: The `generate_etag` callback can now return
869 `undefined` to conditionally avoid generating
870 an etag.
871 * *2.9*: An `AcceptCallback` can now return `{created, URI}` or
872 `{see_other, URI}`. The return value `{true, URI}`
873 is deprecated.
874 * *2.7*: The media type wildcard in `content_types_accepted`
875 is now documented.
876 * *2.6*: The callback `rate_limited` was added.
877 * *2.1*: The `switch_handler` return value was added.
878 * *1.0*: Behavior introduced.
879
880 == See also
881
882 link:man:cowboy(7)[cowboy(7)],
883 link:man:cowboy_handler(3)[cowboy_handler(3)]