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:

    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
    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 cowboy_req:set_resp_body(3).

  allowed_methods
    allowed_methods(Req, State) -> {Result, Req, State}

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

Return the list of allowed methods.

  allow_missing_post
    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
    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.

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

    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
    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

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.

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.

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.

  content_types_provided
    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}]

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.

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.

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:

    req() :: #{
        media_type => ParsedMime
    }

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

    req() :: #{
        charset => binary()  %% lowercase; case insensitive
    }

  delete_completed
    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
    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
    expires(Req, State) -> {Result, Req, State}

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

Return the resource's expiration date.

  forbidden
    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
    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
    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
    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
    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
    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.

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

    req() :: #{
        language => binary()  %% lowercase; case insensitive
    }

  last_modified
    last_modified(Req, State) -> {Result, Req, State}

    Result  :: calendar:datetime() | undefined
    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.

When undefined is returned, no last-modified header is added to response. Can be useful if you save timestamp on store action in memory and lose it after restart.

  malformed_request
    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
    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
    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
    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
    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
    previously_existed(Req, State) -> {Result, Req, State}

    Result  :: boolean()
    Default :: false

Return whether the resource existed previously.

  ProvideCallback
    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.

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
    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
    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
    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:

    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
    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
    resource_exists(Req, State) -> {Result, Req, State}

    Result  :: boolean()
    Default :: true

Return whether the resource exists.

  service_available
    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
    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
    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
    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
    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.14: The last_modified callback is now type correct when returning undefined to avoid responding a last-modified header.
    • 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

cowboy(7), cowboy_handler(3)