MyNixOS website logo
Description

Automatically generate Elm clients for Servant APIs.

Please see the README on GitHub at https://github.com/folq/servant-to-elm#readme

servant-to-elm Hackage

This is a library for generating Elm client libraries from Servant API definitions.

See haskell-to-elm for background information and a more elaborate motivation.

Basic usage

Given a Servant API like the following

type UserAPI
  = "user" :> Get '[JSON] User
  :<|> "user" :> ReqBody '[JSON] User :> PostNoContent '[JSON] NoContent

we can generate the Elm code for making requests against it as follows:

main :: IO ()
main = do
  let
    definitions =
      map (elmEndpointDefinition "Config.urlBase" ["Api"]) (elmEndpoints @UserAPI)
      <> jsonDefinitions @User

    modules =
      Pretty.modules $
        Simplification.simplifyDefinition <$> definitions

  forM_ (HashMap.toList modules) $ \(_moduleName, contents) ->
    print contents

Running main prints:

module Api exposing (..)

import Api.User
import Config
import Http
import Json.Decode


getUser : Cmd (Result (Http.Error , Maybe { metadata : Http.Metadata
    , body : String }) Api.User.User)
getUser =
    Http.request { method = "GET"
    , headers = []
    , url = Config.urlBase ++ "/user"
    , body = Http.emptyBody
    , expect = Http.expectStringResponse identity (\a -> case a of
        Http.BadUrl_ b ->
            Err (Http.BadUrl b , Nothing)

        Http.Timeout_ ->
            Err (Http.Timeout , Nothing)

        Http.NetworkError_ ->
            Err (Http.NetworkError , Nothing)

        Http.BadStatus_ b c ->
            Err (Http.BadStatus b.statusCode , Just { metadata = b, body = c })

        Http.GoodStatus_ b c ->
            Result.mapError (\d -> (Http.BadBody (Json.Decode.errorToString d) , Just { metadata = b
            , body = c })) (Json.Decode.decodeString Api.User.decoder c))
    , timeout = Nothing
    , tracker = Nothing }


postUser : Api.User.User -> Cmd (Result (Http.Error , Maybe { metadata : Http.Metadata
    , body : String }) ())
postUser a =
    Http.request { method = "POST"
    , headers = []
    , url = Config.urlBase ++ "/user"
    , body = Http.jsonBody (Api.User.encoder a)
    , expect = Http.expectStringResponse identity (\b -> case b of
        Http.BadUrl_ c ->
            Err (Http.BadUrl c , Nothing)

        Http.Timeout_ ->
            Err (Http.Timeout , Nothing)

        Http.NetworkError_ ->
            Err (Http.NetworkError , Nothing)

        Http.BadStatus_ c d ->
            Err (Http.BadStatus c.statusCode , Just { metadata = c, body = d })

        Http.GoodStatus_ c d ->
            if d == "" then
                Ok ()

            else
                Err (Http.BadBody "Expected the response body to be empty" , Just { metadata = c
                , body = d }))
    , timeout = Nothing
    , tracker = Nothing }
module Api.User exposing (..)

import Json.Decode
import Json.Decode.Pipeline
import Json.Encode


type alias User =
    { name : String, age : Int }


encoder : User -> Json.Encode.Value
encoder a =
    Json.Encode.object [ ("name" , Json.Encode.string a.name)
    , ("age" , Json.Encode.int a.age) ]


decoder : Json.Decode.Decoder User
decoder =
    Json.Decode.succeed User |>
    Json.Decode.Pipeline.required "name" Json.Decode.string |>
    Json.Decode.Pipeline.required "age" Json.Decode.int

In an actual project we would be writing the code to disk instead of printing it.

See this file for the full code with imports.

Auth-protected routes

If you use AuthProtect from Servant.API.Experimental.Auth, the following code can be used:

instance HasElmEndpoints api => HasElmEndpoints (AuthProtect "auth" :> api) where
  elmEndpoints' = elmEndpoints' @(Header' '[ Required, Strict] "Authorization" Token :> api)

This makes endpoints under AuthProtect "auth" take an extra Token parameter which are added as authorization headers to the requests. This assumes that Token has appropriate instances for HasElmType and HasElmEncoder Text.

Related projects

Libraries that use or are used by servant-to-elm:

  • haskell-to-elm generates Elm types and JSON encoders and decoders from Haskell types.
  • elm-syntax defines Haskell ASTs for Elm's syntax, and lets us pretty-print it.
  • haskell-to-elm-test does end-to-end testing of this library.

Others:

Metadata

Version

0.4.3.0

Platforms (77)

    Darwin
    FreeBSD
    Genode
    GHCJS
    Linux
    MMIXware
    NetBSD
    none
    OpenBSD
    Redox
    Solaris
    WASI
    Windows
Show all
  • aarch64-darwin
  • aarch64-freebsd
  • aarch64-genode
  • aarch64-linux
  • aarch64-netbsd
  • aarch64-none
  • aarch64-windows
  • aarch64_be-none
  • arm-none
  • armv5tel-linux
  • armv6l-linux
  • armv6l-netbsd
  • armv6l-none
  • armv7a-darwin
  • armv7a-linux
  • armv7a-netbsd
  • armv7l-linux
  • armv7l-netbsd
  • avr-none
  • i686-cygwin
  • i686-darwin
  • i686-freebsd
  • i686-genode
  • i686-linux
  • i686-netbsd
  • i686-none
  • i686-openbsd
  • i686-windows
  • javascript-ghcjs
  • loongarch64-linux
  • m68k-linux
  • m68k-netbsd
  • m68k-none
  • microblaze-linux
  • microblaze-none
  • microblazeel-linux
  • microblazeel-none
  • mips-linux
  • mips-none
  • mips64-linux
  • mips64-none
  • mips64el-linux
  • mipsel-linux
  • mipsel-netbsd
  • mmix-mmixware
  • msp430-none
  • or1k-none
  • powerpc-netbsd
  • powerpc-none
  • powerpc64-linux
  • powerpc64le-linux
  • powerpcle-none
  • riscv32-linux
  • riscv32-netbsd
  • riscv32-none
  • riscv64-linux
  • riscv64-netbsd
  • riscv64-none
  • rx-none
  • s390-linux
  • s390-none
  • s390x-linux
  • s390x-none
  • vc4-none
  • wasm32-wasi
  • wasm64-wasi
  • x86_64-cygwin
  • x86_64-darwin
  • x86_64-freebsd
  • x86_64-genode
  • x86_64-linux
  • x86_64-netbsd
  • x86_64-none
  • x86_64-openbsd
  • x86_64-redox
  • x86_64-solaris
  • x86_64-windows