lukewestby/elm-http-builder/3.0.0

NOTE: this package is not compatible with Elm 0.19.1

HttpBuilder

Extra helpers for more easily building Http requests that require greater configuration than what is provided by elm-http out of the box.

Send a request

BodyReader a
-> BodyReader b
-> RequestBuilder
-> Task (Error b) (Response a)

Once you're finished building up a request, send it with readers for the successful response value as well as the server error response value.

-- In this example a succesful response from the server looks like
-- ["string", "string", "string"], and an error body might look like
-- "Bad Request" or something similar, such that it is a string that is
-- not valid JSON (it would need to look like "\"Bad Request\"" to be
-- decodable as JSON).


successDecoder : Json.Decode.Decoder (List String)
successDecoder =
    Json.Decode.list Json.Decode.string


get "https://example.com/api/items"
    |> withHeader "Content-Type" "application/json"
    |> withTimeout (10 * Time.second)
    |> send (jsonReader successDecoder) stringReader

Start a request

A type for chaining request configuration

url : String -> List ( String, String ) -> String

Construct a url using String, String key value pairs for the query string. See Http.url.

googleUrl =
    url "https://google.com" [("q", "elm")]
get : String -> RequestBuilder

Start building a GET request with a given URL

get "https://example.com/api/items/1"
post : String -> RequestBuilder

Start building a POST request with a given URL

post "https://example.com/api/items"
put : String -> RequestBuilder

Start building a PUT request with a given URL

put "https://example.com/api/items/1"
patch : String -> RequestBuilder

Start building a PATCH request with a given URL

patch "https://example.com/api/items/1"
delete : String -> RequestBuilder

Start building a DELETE request with a given URL

delete "https://example.com/api/items/1"
options : String -> RequestBuilder

Start building a OPTIONS request with a given URL

options "https://example.com/api/items/1"
trace : String -> RequestBuilder

Start building a TRACE request with a given URL

trace "https://example.com/api/items/1"

Configure request properties

withHeader : String -> String -> RequestBuilder -> RequestBuilder

Add a single header to a request

get "https://example.com/api/items/1"
    |> withHeader "Content-Type" "application/json"
withHeaders : List ( String, String ) -> RequestBuilder -> RequestBuilder

Add many headers to a request

get "https://example.com/api/items/1"
    |> withHeaders [("Content-Type", "application/json"), ("Accept", "application/json")]
withBody : Body -> RequestBuilder -> RequestBuilder

Add a body to a request for requests that allow bodies.

post "https://example.com/api/items/1"
    |> withHeader "Content-Type" "application/json"
    |> withBody (Http.string """{ "sortBy": "coolness", "take": 10 }""")
withStringBody : String -> RequestBuilder -> RequestBuilder

Convenience function for adding a string body to a request

post "https://example.com/api/items/1"
    |> withHeader "Content-Type" "application/json"
    |> withStringBody """{ "sortBy": "coolness", "take": 10 }"""
withJsonBody : Value -> RequestBuilder -> RequestBuilder

Convenience function for adding a JSON body to a request

params = Json.Encode.object
    [ ("sortBy", Json.Encode.string "coolness")
    , ("take", Json.Encode.int 10)
    ]


post "https://example.com/api/items/1"
    |> withHeader "Content-Type" "application/json"
    |> withJsonBody params
withMultipartBody : List Data -> RequestBuilder -> RequestBuilder

Convenience function for adding a multiplart body to a request

post "https://example.com/api/items/1"
    |> withMultipartBody [Http.stringData "user" (JS.encode user)]
withMultipartStringBody : List ( String, String ) -> RequestBuilder -> RequestBuilder

Convience function for adding multipart bodies composed of String, String key-value pairs. Since Http.stringData is currently the only Http.Data creator having this function removes the need to use the Http.Data type in your type signatures.

post "https://example.com/api/items/1"
    |> withMultipartStringBody [("user", JS.encode user)]
withUrlEncodedBody : List ( String, String ) -> RequestBuilder -> RequestBuilder

Convenience function for adding url encoded bodies

post "https://example.com/api/whatever"
    |> withUrlEncodedBody [("user", "Evan"), ("pwd", "secret")]

Configure settings

withTimeout : Time -> RequestBuilder -> RequestBuilder

Set the timeout setting on the request

get "https://example.com/api/items/1"
    |> withTimeout (10 * Time.second)
withMimeType : String -> RequestBuilder -> RequestBuilder

Set the desired type of the response for the request, works via [XMLHttpRequest#overrideMimeType()](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#overrideMimeType())

get "https://example.com/api/items/1"
    |> withMimeType (onProgressHandler)
withCredentials : RequestBuilder -> RequestBuilder

Set the withCredentials flag on the request to True. Works via XMLHttpRequest#withCredentials

get "https://example.com/api/items/1"
    |> withCredentials

Custom configurations

withCacheBuster : RequestBuilder -> RequestBuilder

Injects a cache busting url param into the url with the current timestamp as the value to prevent the server from caching responses get "https://example.com/api/items/1" |> withCredentials

withZeroStatusAllowed : RequestBuilder -> RequestBuilder

Explicitly allows a require for a file:// url with a response status code of 0 to pass through successfully. This is a common issue when dealing with file:// urls in environments like cordova, and using this function will allow you to work around the problem on an opt-in basis.

Parse the response

type alias BodyReader a =
Value -> Result String a

A function for transforming raw response bodies into a useful value. Plain string and JSON decoding readers are provided, and the string reader can be used as a basis for more custom readers. When future Http value types become supported matching readers will be added to extract them.

stringReader : BodyReader String

Attempts to read a raw response body as a plain text string, failing if the body is not readable as a string.

jsonReader : Decoder a -> BodyReader a

Attempts to decode the raw response body with the given Json.Decode.Decoder, failing if the body is malformed or not readable as a string.

unitReader : BodyReader ()

Totally discards the content of a raw response body and reads nothing, returning () as the data value. Great for discarding error response bodies if they just look like "Not Found" or whatever and aren't really useful.

type Error a
= UnexpectedPayload String
| NetworkError
| Timeout
| BadResponse (Response a)

Indicates that some kind of failure occured along the path of making and receiving the request. This includes a timeout or network issue, a failure to parse the response body, or a status code outside the 200 range. In the case that the error is due to a non-2xx response code, the full response is provided and the data decoded as JSON using the decoder for errors passed to send.

type alias Response a =
{ data : a
, status : Int
, statusText : String
, headers : Dict String String
, url : String
}

Represents a response from the server, including both a decoded JSON payload and basic network information.

Inspect the request

toRequest : RequestBuilder -> Request

Extract the Http.Request component of the builder, for introspection and testing

toSettings : RequestBuilder -> Settings

Extract the Http.Settings component of the builder, for introspection and testing

type alias Request =
Request

Re-export Http.Request

type alias Settings =
Settings

Re-export Http.Settings