Make HTTP requests in Elm.
import Http
import Json.Decode as Decode
-- GET A STRING
getWarAndPeace : Http.Request String
getWarAndPeace =
Http.getString "https://example.com/books/war-and-peace"
-- GET JSON
getMetadata : Http.Request Metadata
getMetadata =
Http.get "https://example.com/books/war-and-peace/metadata" decodeMetadata
type alias Metadata =
{ author : String
, pages : Int
}
decodeMetadata : Decode.Decoder Metadata
decodeMetadata =
Decode.map2 Metadata
(Decode.field "author" Decode.string)
(Decode.field "pages" Decode.int)
-- SEND REQUESTS
type Msg
= LoadMetadata (Result Http.Error Metadata)
send : Cmd Msg
send =
Http.send LoadMetadata getMetadata
- GET requests - demo and code
- Download progress - demo and code
To understand how HTTP works in Elm, check out:
- The HTTP example in the guide to see a simple usage with some explanation.
- The Elm Architecture to understand how HTTP fits into Elm in a more complete way. This will explain concepts like
Cmd
andSub
that appear in this package.