cowboy_rest.asciidoc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. = cowboy_rest(3)
  2. == Name
  3. cowboy_rest - REST handlers
  4. == Description
  5. The module `cowboy_rest` implements the HTTP state machine.
  6. Implementing REST handlers is not enough to provide a REST
  7. interface; this interface must also follow the REST
  8. constraints including HATEOAS (hypermedia as the engine
  9. of application state).
  10. == Callbacks
  11. REST handlers implement the following interface:
  12. [source,erlang]
  13. ----
  14. init(Req, State)
  15. -> {cowboy_rest, Req, State}
  16. Callback(Req, State)
  17. -> {Result, Req, State}
  18. | {stop, Req, State}
  19. terminate(Reason, Req, State) -> ok %% optional
  20. Req :: cowboy_req:req()
  21. State :: any()
  22. Reason :: normal
  23. | {crash, error | exit | throw, any()}
  24. Callback - see below
  25. Result - see below
  26. Default - see below
  27. ----
  28. The `init/2` callback is common to all handlers. To switch
  29. to the REST handler behavior, it must return `cowboy_rest`
  30. as the first element of the tuple.
  31. The `Callback/2` above represents all the REST-specific
  32. callbacks. They are described in the following section
  33. of this manual. REST-specific callbacks differ by their
  34. name, semantics, result and default values. The default
  35. value is the one used when the callback has not been
  36. implemented. They otherwise all follow the same interface.
  37. The `stop` tuple can be returned to stop REST processing.
  38. If no response was sent before then, Cowboy will send a
  39. '204 No Content'.
  40. The optional `terminate/3` callback will ultimately be called
  41. with the reason for the termination of the handler.
  42. Cowboy will terminate the process right after this. There
  43. is no need to perform any cleanup in this callback.
  44. The following terminate reasons are defined for loop handlers:
  45. normal::
  46. The handler terminated normally.
  47. {crash, Class, Reason}::
  48. A crash occurred in the handler. `Class` and `Reason` can be
  49. used to obtain more information about the crash. The function
  50. `erlang:get_stacktrace/0` can also be called to obtain the
  51. stacktrace of the process when the crash occurred.
  52. == REST callbacks
  53. === AcceptCallback
  54. [source,erlang]
  55. ----
  56. AcceptCallback(Req, State) -> {Result, Req, State}
  57. Result :: true | {true, URI :: iodata()} | false}
  58. Default - crash
  59. ----
  60. Process the request body.
  61. This function should create or update the resource using the
  62. request body.
  63. For PUT requests, the body is a representation of the resource
  64. that is being created or replaced.
  65. For POST requests, the body is typically application-specific
  66. instructions on how to process the request, but it may also
  67. be a representation of the resource. When creating a new
  68. resource with POST at a different location, return `{true, URI}`
  69. with `URI` the new location.
  70. For PATCH requests, the body is a series of instructions on
  71. how to update the resource. Patch files or JSON Patch are
  72. examples of such media types.
  73. A response body may be sent. The appropriate media type, charset
  74. and language for the response can be retrieved from the Req
  75. object using the `media_type`, `charset` and `language` keys,
  76. respectively. The body can be set using
  77. link:man:cowboy_req:set_resp_body(3)[cowboy_req:set_resp_body(3)].
  78. === allowed_methods
  79. [source,erlang]
  80. ----
  81. allowed_methods(Req, State) -> {Result, Req, State}
  82. Result :: [binary()] %% case sensitive
  83. Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]
  84. ----
  85. Return the list of allowed methods.
  86. === allow_missing_post
  87. [source,erlang]
  88. ----
  89. allow_missing_post(Req, State) -> {Result, Req, State}
  90. Result :: boolean()
  91. Default :: true
  92. ----
  93. Return whether POST is allowed when the resource doesn't exist.
  94. Returning `true` here means that a new resource will be
  95. created. The URI for the newly created resource should be
  96. returned from the `AcceptCallback` function.
  97. === charsets_provided
  98. [source,erlang]
  99. ----
  100. charsets_provided(Req, State) -> {Result, Req, State}
  101. Result :: [binary()] %% lowercase; case insensitive
  102. Default - skip this step
  103. ----
  104. Return the list of charsets the resource provides in order
  105. of preference.
  106. During content negotiation Cowboy will pick the most
  107. appropriate charset for the client. The client advertises
  108. charsets it prefers with the accept-charset header. When
  109. that header is missing, Cowboy picks the first charset
  110. from the resource.
  111. // @todo We should explain precisely how charsets are picked.
  112. Cowboy will add the negotiated `charset` to the Req object
  113. after this step completes:
  114. [source,erlang]
  115. ----
  116. req() :: #{
  117. charset => binary() %% lowercase; case insensitive
  118. }
  119. ----
  120. === content_types_accepted
  121. [source,erlang]
  122. ----
  123. content_types_accepted(Req, State) -> {Result, Req, State}
  124. Result :: [{binary() | ParsedMime, AcceptCallback :: atom()}]
  125. ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
  126. Params :: [{Key :: binary(), Value :: binary()}]
  127. Default - crash
  128. ----
  129. // @todo Case sensitivity of parsed mime content?
  130. Return the list of media types the resource accepts in
  131. order of preference.
  132. A media type is made of different parts. The media type
  133. `text/html;charset=utf-8` is of type `text`, subtype `html`
  134. and has a single parameter `charset` with value `utf-8`.
  135. // @todo Cowboy needs to ignore the boundary parameter for
  136. // multipart, as we never want to match against it. Or allow
  137. // ignoring specific parameters at the very least.
  138. Cowboy will match the content-type request header against
  139. the media types the server accepts and select the appropriate
  140. callback. When that header is missing, or when the server does not
  141. accept this media type, the request fails and an error response
  142. is returned. Cowboy will execute the callback immediately otherwise.
  143. // @todo We should explain precisely how media types are picked.
  144. An empty parameters list `[]` means that no parameters will be
  145. accepted. When any parameter is acceptable, the tuple form
  146. should be used with parameters as the atom `'*'`.
  147. Cowboy treats all parameters as case sensitive, except for the
  148. `charset` parameter, which is known to be case insensitive. You
  149. should therefore always provide the charset as a lowercase
  150. binary string.
  151. // @todo Maybe this should be in the user guide instead.
  152. //This function will be called for POST, PUT and PATCH requests.
  153. //It is entirely possible to define different callbacks for different
  154. //methods if the handling of the request differs. Simply verify
  155. //what the method is with `cowboy_req:method/1` and return a
  156. //different list for each methods.
  157. === content_types_provided
  158. [source,erlang]
  159. ----
  160. content_types_provided(Req, State) -> {Result, Req, State}
  161. Result :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
  162. ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
  163. Params :: [{Key :: binary(), Value :: binary()}]
  164. Default - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
  165. ----
  166. // @todo Case sensitivity of parsed mime content?
  167. // @todo Space required for the time being: https://github.com/spf13/hugo/issues/2398
  168. Return the list of media types the resource provides in
  169. order of preference.
  170. A media type is made of different parts. The media type
  171. `text/html;charset=utf-8` is of type `text`, subtype `html`
  172. and has a single parameter `charset` with value `utf-8`.
  173. // @todo Cowboy needs to ignore the boundary parameter for
  174. // multipart, as we never want to match against it. Or allow
  175. // ignoring specific parameters at the very least.
  176. During content negotiation Cowboy will pick the most appropriate
  177. media type for the client. The client advertises media types it
  178. prefers with the accept header. When that header is missing,
  179. the content negotiation fails and an error response is returned.
  180. The callback given for the selected media type will be called
  181. at the end of the execution of GET and HEAD requests when a
  182. representation must be sent to the client.
  183. // @todo We should explain precisely how media types are picked.
  184. An empty parameters list `[]` means that no parameters will be
  185. accepted. When any parameter is acceptable, the tuple form
  186. should be used with parameters as the atom `'*'`.
  187. Cowboy treats all parameters as case sensitive, except for the
  188. `charset` parameter, which is known to be case insensitive. You
  189. should therefore always provide the charset as a lowercase
  190. binary string.
  191. Cowboy will add the negotiated `media_type` to the Req object
  192. after this step completes:
  193. [source,erlang]
  194. ----
  195. req() :: #{
  196. media_type => ParsedMime
  197. }
  198. ----
  199. // @todo Case sensitivity of parsed mime content?
  200. === delete_completed
  201. [source,erlang]
  202. ----
  203. delete_completed(Req, State) -> {Result, Req, State}
  204. Result :: boolean()
  205. Default :: true
  206. ----
  207. Return whether the resource has been fully deleted from the
  208. system, including from any internal cache.
  209. Returning `false` will result in a '202 Accepted' response
  210. being sent instead of a '200 OK' or '204 No Content'.
  211. === delete_resource
  212. [source,erlang]
  213. ----
  214. delete_resource(Req, State) -> {Result, Req, State}
  215. Result :: boolean()
  216. Default :: false
  217. ----
  218. Delete the resource.
  219. Cowboy will send an error response when this function
  220. returns `false`.
  221. === expires
  222. [source,erlang]
  223. ----
  224. expires(Req, State) -> {Result, Req, State}
  225. Result :: calendar:datetime() | binary() | undefined
  226. Default :: undefined
  227. ----
  228. Return the resource's expiration date.
  229. === forbidden
  230. [source,erlang]
  231. ----
  232. forbidden(Req, State) -> {Result, Req, State}
  233. Result :: boolean()
  234. Default :: false
  235. ----
  236. Return whether access to the resource is forbidden.
  237. A '403 Forbidden' response will be sent if this
  238. function returns `true`. This status code means that
  239. access is forbidden regardless of authentication,
  240. and that the request shouldn't be repeated.
  241. === generate_etag
  242. [source,erlang]
  243. ----
  244. generate_etag(Req, State) -> {Result, Req, State}
  245. Result :: binary() | {weak | strong, binary()}
  246. Default - no etag value
  247. ----
  248. Return the entity tag of the resource.
  249. When a binary is returned, the value is automatically
  250. parsed to a tuple. The binary must be in the same
  251. format as the etag header, including quotes.
  252. === is_authorized
  253. [source,erlang]
  254. ----
  255. is_authorized(Req, State) -> {Result, Req, State}
  256. Result :: true | {false, AuthHeader :: iodata()}
  257. Default - true
  258. ----
  259. Return whether the user is authorized to perform the action.
  260. This function should be used to perform any necessary
  261. authentication of the user before attempting to perform
  262. any action on the resource.
  263. When authentication fails, the `AuthHeader` value will
  264. be sent in the www-authenticate header for the
  265. '401 Unauthorized' response.
  266. === is_conflict
  267. [source,erlang]
  268. ----
  269. is_conflict(Req, State) -> {Result, Req, State}
  270. Result :: boolean()
  271. Default :: false
  272. ----
  273. Return whether the PUT request results in a conflict.
  274. A '409 Conflict' response is sent when `true`.
  275. === known_methods
  276. [source,erlang]
  277. ----
  278. known_methods(Req, State) -> {Result, Req, State}
  279. Result :: [binary()] %% case sensitive
  280. Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>,
  281. <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
  282. ----
  283. Return the list of known methods.
  284. The full list of methods known by the server should be
  285. returned, regardless of their use in the resource.
  286. The default value lists the methods Cowboy knows and
  287. implement in `cowboy_rest`.
  288. === languages_provided
  289. [source,erlang]
  290. ----
  291. languages_provided(Req, State) -> {Result, Req, State}
  292. Result :: [binary()] %% lowercase; case insensitive
  293. Default - skip this step
  294. ----
  295. Return the list of languages the resource provides in order
  296. of preference.
  297. During content negotiation Cowboy will pick the most
  298. appropriate language for the client. The client advertises
  299. languages it prefers with the accept-language header. When
  300. that header is missing, Cowboy picks the first language
  301. from the resource.
  302. // @todo We should explain precisely how languages are picked.
  303. Cowboy will add the negotiated `language` to the Req object
  304. after this step completes:
  305. [source,erlang]
  306. ----
  307. req() :: #{
  308. language => binary() %% lowercase; case insensitive
  309. }
  310. ----
  311. === last_modified
  312. [source,erlang]
  313. ----
  314. last_modified(Req, State) -> {Result, Req, State}
  315. Result :: calendar:datetime()
  316. Default - no last modified value
  317. ----
  318. Return the resource's last modification date.
  319. This date will be used to test against the if-modified-since
  320. and if-unmodified-since headers, and sent as the last-modified
  321. header in the response to GET and HEAD requests.
  322. === malformed_request
  323. [source,erlang]
  324. ----
  325. malformed_request(Req, State) -> {Result, Req, State}
  326. Result :: boolean()
  327. Default :: false
  328. ----
  329. Return whether the request is malformed.
  330. A request is malformed when a component required by the
  331. resource is invalid. This may include the query string
  332. or individual headers. They should be parsed and validated
  333. in this function. The body should not be read at this point.
  334. === moved_permanently
  335. [source,erlang]
  336. ----
  337. moved_permanently(Req, State) -> {Result, Req, State}
  338. Result :: {true, URI :: iodata()} | false
  339. Default :: false
  340. ----
  341. Return whether the resource was permanently moved, and
  342. what its new location is.
  343. === moved_temporarily
  344. [source,erlang]
  345. ----
  346. moved_temporarily(Req, State) -> {Result, Req, State}
  347. Result :: {true, URI :: iodata()} | false
  348. Default :: false
  349. ----
  350. Return whether the resource was temporarily moved, and
  351. what its new location is.
  352. === multiple_choices
  353. [source,erlang]
  354. ----
  355. multiple_choices(Req, State) -> {Result, Req, State}
  356. Result :: boolean()
  357. Default :: false
  358. ----
  359. Return whether the client should engage in reactive
  360. negotiation.
  361. Return `true` when the server has multiple representations
  362. of a resource, each with their specific identifier, but is
  363. unable to determine which is best for the client. For
  364. example an image might have different sizes and the server
  365. is unable to determine the capabilities of the client.
  366. When returning `true` the server should send a body with
  367. links to the different representations. If the server has
  368. a preferred representation it can send its link inside a
  369. location header.
  370. === options
  371. [source,erlang]
  372. ----
  373. options(Req, State) -> {ok, Req, State}
  374. ----
  375. Respond to an OPTIONS request.
  376. The response should inform the client the communication
  377. options available for this resource. By default Cowboy
  378. will send a '200 OK' response with the allow header set.
  379. === previously_existed
  380. [source,erlang]
  381. ----
  382. previously_existed(Req, State) -> {Result, Req, State}
  383. Result :: boolean()
  384. Default :: false
  385. ----
  386. Return whether the resource existed previously.
  387. === ProvideCallback
  388. [source,erlang]
  389. ----
  390. ProvideCallback(Req, State) -> {Result, Req, State}
  391. Result :: cowboy_req:resp_body()
  392. Default - crash
  393. ----
  394. Return the response body.
  395. The response body can be provided either as the actual data
  396. to be sent or a tuple indicating which file to send.
  397. This function is called for both GET and HEAD requests. For
  398. the latter the body is not sent, however.
  399. // @todo Perhaps we can optimize HEAD requests and just
  400. // allow calculating the length instead of returning the
  401. // whole thing.
  402. Note that there used to be a way to stream the response body.
  403. It was temporarily removed and will be added back in a later
  404. release.
  405. // @todo Add a way to switch to loop handler for streaming the body.
  406. === resource_exists
  407. [source,erlang]
  408. ----
  409. resource_exists(Req, State) -> {Result, Req, State}
  410. Result :: boolean()
  411. Default :: true
  412. ----
  413. Return whether the resource exists.
  414. === service_available
  415. [source,erlang]
  416. ----
  417. service_available(Req, State) -> {Result, Req, State}
  418. Result :: boolean()
  419. Default :: true
  420. ----
  421. Return whether the service is available.
  422. A '503 Service Unavailable' response will be sent when this
  423. function returns `false`.
  424. === uri_too_long
  425. [source,erlang]
  426. ----
  427. uri_too_long(Req, State) -> {Result, Req, State}
  428. Result :: boolean()
  429. Default :: false
  430. ----
  431. Return whether the requested URI is too long.
  432. This function can be used to further restrict the length
  433. of the URI for this specific resource.
  434. === valid_content_headers
  435. [source,erlang]
  436. ----
  437. valid_content_headers(Req, State) -> {Result, Req, State}
  438. Result :: boolean()
  439. Default :: true
  440. ----
  441. Return whether the content headers are valid.
  442. This callback can be used to reject requests that have
  443. invalid content header values, for example an unsupported
  444. content-encoding.
  445. === valid_entity_length
  446. [source,erlang]
  447. ----
  448. valid_entity_length(Req, State) -> {Result, Req, State}
  449. Result :: boolean()
  450. Default :: true
  451. ----
  452. Return whether the request body length is within acceptable boundaries.
  453. A '413 Request Entity Too Large' response will be sent if this
  454. function returns `false`.
  455. === variances
  456. [source,erlang]
  457. ----
  458. variances(Req, State) -> {Result, Req, State}
  459. Result :: [binary()] %% case insensitive
  460. Default :: []
  461. ----
  462. Return the list of request headers that affect the
  463. representation of the resource.
  464. Cowboy automatically adds the accept, accept-charset and
  465. accept-language headers when necessary.
  466. == See also
  467. link:man:cowboy(7)[cowboy(7)],
  468. link:man:cowboy_handler(3)[cowboy_handler(3)]