HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Moduleservant-foreign-0.16.1Haskell2010

Servant.Foreign

Generalizes all the data needed to make code generation work with arbitrary programming languages.

See documentation of HasForeignType for a simple example. listFromAPI returns a list of all your endpoints and their foreign types, given a mapping from Haskell types to foreign types (conventionally called ftypes below).

  • 104 types
  • 22 classes
  • 37 values

Main API

7 declarations
datadata Req ftype
#

Full description of an endpoint in your API, generated by listFromAPI. It should give you all the information needed to generate foreign language bindings.

Every field containing ftype will use the foreign type mapping specified via HasForeignType (see its docstring on how to set that up).

See https://docs.servant.dev/en/stable/tutorial/ApiType.html for accessible documentation of the possible content of an endpoint.

Constructors

  • Req
    • _reqUrl :: Url ftype

      Full list of URL segments, including captures

    • _reqMethod :: Method

      "GET"/"POST"/"PUT"/…

    • _reqHeaders :: [HeaderArg ftype]

      Headers required by this endpoint, with their type

    • _reqBody :: Maybe ftype

      Foreign type of the expected request body (ReqBody), if any

    • _reqReturnType :: Maybe ftype

      The foreign type of the response, if any

    • _reqFuncName :: FunctionName

      The URL segments rendered in a way that they can be easily concatenated into a canonical function name

    • _reqBodyContentType :: ReqBodyContentType

      The content type the request body is transferred as.

      This is a severe limitation of servant-foreign currently, as we only allow the content type to be JSON no user-defined content types. (ReqBodyMultipart is not actually implemented.)

      Thus, any routes looking like this will work:

      "foo" :> Get '[JSON] Foo

      while routes like

      "foo" :> Get '[MyFancyContentType] Foo

      will fail with an error like

      • JSON expected in list '[MyFancyContentType]
Instances4GenerateList, Eq, Data, Show
  • GenerateList ftype (Req ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Eq ftype => Eq (Req ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Data ftype => Data (Req ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Show ftype => Show (Req ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
classclass HasForeignType (lang :: k) ftype (a :: k1) where
#

HasForeignType maps Haskell types with types in the target language of your backend. For example, let's say you're implementing a backend to some language X, and you want a Text representation of each input/output type mentioned in the API:

-- First you need to create a dummy type to parametrize your
-- instances.
data LangX

-- Otherwise you define instances for the types you need
instance HasForeignType LangX Text Int where
   typeFor _ _ _ = "intX"

-- Or for example in case of lists
instance HasForeignType LangX Text a => HasForeignType LangX Text [a] where
   typeFor lang ftype _ = "listX of " <> typeFor lang ftype (Proxy :: Proxy a)

Finally to generate list of information about all the endpoints for an API you create a function of a form:

getEndpoints :: (HasForeign LangX Text api, GenerateList Text (Foreign Text api))
             => Proxy api -> [Req Text]
getEndpoints api = listFromAPI (Proxy :: Proxy LangX) (Proxy :: Proxy Text) api
-- If language __X__ is dynamically typed then you can use
-- a predefined NoTypes parameter with the NoContent output type:
getEndpoints :: (HasForeign NoTypes NoContent api, GenerateList Text (Foreign NoContent api))
             => Proxy api -> [Req NoContent]
getEndpoints api = listFromAPI (Proxy :: Proxy NoTypes) (Proxy :: Proxy NoContent) api

Methods

Instances1HasForeignType
classclass GenerateList ftype reqs where
#

Utility class used by listFromAPI which computes the data needed to generate a function for each endpoint and hands it all back in a list.

Methods

Instances3GenerateList
classclass HasForeign (lang :: k) ftype api where
#

Implementation of the Servant framework types.

Relevant instances: Everything containing HasForeignType.

Associated types

Methods

Instances25HasForeign, …
datadata NoTypes
#

The language definition without any foreign types. It can be used for dynamic languages which do not do type annotations.

Instances1HasForeignType

Subtypes of Req

13 declarations
datadata Url ftype
#

Full endpoint url, with all captures and parameters

Constructors

  • Url
    • _path :: Path ftype

      Url path, list of either static segments or captures

      "foo/{id}/bar"
    • _queryStr :: [QueryArg ftype]

      List of query args

      "?foo=bar&a=b"
    • _frag :: Maybe ftype

      Url fragment.

      Not sent to the HTTP server, so only useful for frontend matters (e.g. inter-page linking).

      #fragmentText
Instances3Eq, Data, Show
  • Eq ftype => Eq (Url ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Data ftype => Data (Url ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Show ftype => Show (Url ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
newtypenewtype Segment ftype
#

A part of the Url’s path.

Constructors

Instances3Eq, Data, Show
  • Eq ftype => Eq (Segment ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Data ftype => Data (Segment ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Show ftype => Show (Segment ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
datadata SegmentType ftype
#

Constructors

  • Static PathSegment

    Static path segment.

    "foo/bar/baz"

    contains the static segments "foo", "bar" and "baz".

  • Cap (Arg ftype)

    A capture.

    "user/{userid}/name"

    would capture the arg userid with type ftype.

Instances3Eq, Data, Show
  • Eq ftype => Eq (SegmentType ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Data ftype => Data (SegmentType ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Show ftype => Show (SegmentType ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
datadata QueryArg ftype
#

Url Query argument.

Urls can contain query arguments, which is a list of key-value pairs. In a typical url, query arguments look like this:

?foo=bar&alist[]=el1&alist[]=el2&aflag

Each pair can be

  • ?foo=bar: a plain key-val pair, either optional or required (QueryParam)

  • ?aflag: a flag (no value, implicitly Bool with default false if it’s missing) (QueryFlag)

  • ?alist[]=el1&alist[]=el2: list of values (QueryParams)

_queryArgType will be set accordingly.

For the plain key-val pairs (QueryParam), _queryArgName’s ftype will be wrapped in a Maybe if the argument is optional.

Constructors

Instances3Eq, Data, Show
  • Eq ftype => Eq (QueryArg ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Data ftype => Data (QueryArg ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Show ftype => Show (QueryArg ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
datadata ArgType
#

Type of a QueryArg.

Instances3Eq, Data, Show
  • Eq ArgTypeDefined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Data ArgTypeDefined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Show ArgTypeDefined in servant-foreign-0.16.1 · Servant.Foreign.Internal
datadata HeaderArg ftype
#

Constructors

Instances3Eq, Data, Show
  • Eq ftype => Eq (HeaderArg ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Data ftype => Data (HeaderArg ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Show ftype => Show (HeaderArg ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
datadata Arg ftype
#

Maps a name to the foreign type that belongs to the annotated value.

Used for header args, query args, and capture args.

Constructors

  • Arg
    • _argName :: PathSegment

      The name to be captured.

      Only for capture args it really denotes a path segment.

    • _argType :: ftype

      Foreign type the associated value will have

Instances3Eq, Data, Show
  • Eq ftype => Eq (Arg ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Data ftype => Data (Arg ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • Show ftype => Show (Arg ftype)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
newtypenewtype FunctionName
#

Canonical name of the endpoint, can be used to generate a function name.

You can use the functions in Servant.Foreign.Inflections, like camelCase to transform to Text.

Instances5Eq, Data, Show, Semigroup, Monoid
newtypenewtype PathSegment
#

See documentation of Arg

Instances6Eq, Data, Show, IsString, Semigroup, Monoid

Lenses

15 declarations

Prisms

8 declarations

Re-exports

130 declarations
datadata NoContent
#

A type for responses without content-body.

Instances11Eq, Read, Show, Generic, NFData, HasStatus, …
datadata (:<|>) a b
#

Union of two APIs, first takes precedence in case of overlap.

Example:

Example1 expression
:{type MyApi = "books" :> Get '[JSON] [Book] -- GET /books       :<|> "books" :> ReqBody '[JSON] Book :> Post '[JSON] () -- POST /books:}

Constructors

Instances17Bifoldable, Bifunctor, Bitraversable, Biapplicative, HasForeign, HasLink, …
datadata EmptyAPI
#

An empty API: one which serves nothing. Morally speaking, this should be the unit of :<|>. Implementors of interpretations of API types should treat EmptyAPI as close to the unit as possible.

Instances8Bounded, Enum, Eq, Show, HasLink, HasForeign, …
datadata Capture' (mods :: [Type]) (sym :: Symbol) a
#

Capture which can be modified. For example with Description.

Instances4HasForeign, HasLink, MkLink, Foreign
datadata (:>) (path :: k) a
#

The contained API (second argument) can be found under ("/" ++ path) (path being the first argument).

Example:

Example3 expressions
-- GET /hello/world-- returning a JSON encoded World valuetype MyApi = "hello" :> "world" :> Get '[JSON] World
Instances75HasForeign, HasLink, MkLink, Foreign, …
datadata CaptureAll (sym :: Symbol) a
#

Capture all remaining values from the request path under a certain type a.

Example:

Example2 expressions
-- GET /src/*type MyAPI = "src" :> CaptureAll "segments" Text :> Get '[JSON] SourceFile
Instances4HasForeign, HasLink, MkLink, Foreign
datadata JSON
#
Instances5Accept, MimeRender, MimeUnrender
classclass ReflectMethod (a :: k) where
#

Methods

Instances9ReflectMethod, …
datadata Verb (method :: k1) (statusCode :: Nat) (contentTypes :: [Type]) a
#

Verb is a general type for representing HTTP verbs (a.k.a. methods). For convenience, type synonyms for each verb with a 200 response code are provided, but you are free to define your own:

Example1 expression
type Post204 contentTypes a = Verb 'POST 204 contentTypes a
Instances7HasForeign, HasLink, Generic, AtMostOneFragment, Rep, MkLink, …
  • (Elem JSON list, HasForeignType lang ftype a, ReflectMethod method) => HasForeign lang ftype (Verb method status list a)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • HasLink (Verb m s ct a)Defined in servant-0.20.2 · Servant.Links
  • Generic (Verb method statusCode contentTypes a)Defined in servant-0.20.2 · Servant.API.Verbs
  • AtMostOneFragment (Verb m s ct typ)Defined in servant-0.20.2 · Servant.API.TypeLevel
  • type Rep (Verb method statusCode contentTypes a) = D1 ('MetaData "Verb" "Servant.API.Verbs" "servant-0.20.2-kmMZib8zXn7e8NZPkSX15" 'False) V1Defined in servant-0.20.2 · Servant.API.Verbs
  • type MkLink (Verb m s ct a) r = rDefined in servant-0.20.2 · Servant.Links
  • type Foreign ftype (Verb method status list a) = Req ftypeDefined in servant-foreign-0.16.1 · Servant.Foreign.Internal
datadata NoContentVerb (method :: k1)
#

NoContentVerb is a specific type to represent NoContent responses. It does not require either a list of content types (because there's no content) or a status code (because it should always be 204).

Instances6HasForeign, HasLink, Generic, Rep, MkLink, Foreign
datadata Stream (method :: k1) (status :: Nat) framing contentType a
#

A Stream endpoint for a given method emits a stream of encoded values at a given Content-Type, delimited by a framing strategy. Type synonyms are provided for standard methods.

Instances6HasForeign, HasLink, Generic, Rep, MkLink, Foreign
  • (ct ~ JSON, HasForeignType lang ftype a, ReflectMethod method) => HasForeign lang ftype (Stream method status framing ct a)Defined in servant-foreign-0.16.1 · Servant.Foreign.Internal

    TODO: doesn't taking framing into account.

  • HasLink (Stream m status fr ct a)Defined in servant-0.20.2 · Servant.Links
  • Generic (Stream method status framing contentType a)Defined in servant-0.20.2 · Servant.API.Stream
  • type Rep (Stream method status framing contentType a) = D1 ('MetaData "Stream" "Servant.API.Stream" "servant-0.20.2-kmMZib8zXn7e8NZPkSX15" 'False) V1Defined in servant-0.20.2 · Servant.API.Stream
  • type MkLink (Stream m status fr ct a) r = rDefined in servant-0.20.2 · Servant.Links
  • type Foreign ftype (Stream method status framing ct a) = Req ftypeDefined in servant-foreign-0.16.1 · Servant.Foreign.Internal
datadata Header' (mods :: [Type]) (sym :: Symbol) a
#
Instances9AddHeader, HasForeign, HasResponseHeader, HasLink, BuildHeadersTo, GetHeaders', …
datadata QueryParam' (mods :: [Type]) (sym :: Symbol) a
#

QueryParam which can be Required, Lenient, or modified otherwise.

Instances4HasForeign, HasLink, MkLink, Foreign
datadata QueryParams (sym :: Symbol) a
#

Lookup the values associated to the sym query string parameter and try to extract it as a value of type [a]. This is typically meant to support query string parameters of the form param[]=val1&param[]=val2 and so on. Note that servant doesn't actually require the []s and will fetch the values just fine with param=val1&param=val2, too.

Example:

Example2 expressions
-- /books?authors[]=<author1>&authors[]=<author2>&...type MyApi = "books" :> QueryParams "authors" Text :> Get '[JSON] [Book]
Instances4HasForeign, HasLink, MkLink, Foreign
datadata QueryFlag (sym :: Symbol)
#

Lookup a potentially value-less query string parameter with boolean semantics. If the param sym is there without any value, or if it's there with value "true" or "1", it's interpreted as True. Otherwise, it's interpreted as False.

Example:

Example2 expressions
-- /books?publishedtype MyApi = "books" :> QueryFlag "published" :> Get '[JSON] [Book]
Instances4HasForeign, HasLink, MkLink, Foreign
datadata Fragment a
#

Document the URI fragment in API. Useful in combination with Link.

Example:

Example2 expressions
-- /post#TRACKINGtype MyApi = "post" :> Fragment Text :> Get '[JSON] Tracking
Instances5HasForeign, HasLink, AtMostOneFragment, MkLink, Foreign
datadata Raw
#

Endpoint for plugging in your own Wai Applications.

The given Application will get the request as received by the server, potentially with a modified (stripped) pathInfo if the Application is being routed with :>.

In addition to just letting you plug in your existing WAI Applications, this can also be used with functions from Servant.Server.StaticFiles to serve static files stored in a particular directory on your filesystem

Instances4HasLink, HasForeign, MkLink, Foreign
  • HasLink RawDefined in servant-0.20.2 · Servant.Links
  • HasForeign lang ftype RawDefined in servant-foreign-0.16.1 · Servant.Foreign.Internal
  • type MkLink Raw a = aDefined in servant-0.20.2 · Servant.Links
  • type Foreign ftype Raw = Method -> Req ftypeDefined in servant-foreign-0.16.1 · Servant.Foreign.Internal
datadata ReqBody' (mods :: [Type]) (contentTypes :: [Type]) a
#

Note: ReqBody' is always Required.

Instances4HasForeign, HasLink, MkLink, Foreign
datadata StreamBody' (mods :: [Type]) framing contentType a
#
Instances6HasForeign, HasLink, Generic, Rep, MkLink, Foreign
datadata RemoteHost
#

Provides access to the host or IP address from which the HTTP request was sent.

Instances4HasForeign, HasLink, MkLink, Foreign
datadata IsSecure
#

Was this request made over an SSL connection?

Note that this value will not tell you if the client originally made this request over SSL, but rather whether the current connection is SSL. The distinction lies with reverse proxies. In many cases, the client will connect to a load balancer over SSL, but connect to the WAI handler without SSL. In such a case, the handlers would get NotSecure, but from a user perspective, there is a secure connection.

Constructors

  • Secure

    the connection to the server is secure (HTTPS)

  • NotSecure

    the connection to the server is not secure (HTTP)

Instances10Eq, Ord, Read, Show, Generic, HasForeign, …
typetype Vault = Vault RealWorld
#

A persistent store for values of arbitrary types.

This variant is the simplest and creates keys in the IO monad. See the module Data.Vault.ST if you want to use it with the ST monad instead.

Instances4HasForeign, HasLink, MkLink, Foreign
datadata WithNamedContext (name :: Symbol) (subContext :: [Type]) (subApi :: k)
#

WithNamedContext names a specific tagged context to use for the combinators in the API. (See also in servant-server, Servant.Server.Context.) For example:

type UseNamedContextAPI = WithNamedContext "myContext" '[String] (
    ReqBody '[JSON] Int :> Get '[JSON] Int)

Both the ReqBody and Get combinators will use the WithNamedContext with type tag "myContext" as their context.

Contexts are only relevant for servant-server.

For more information, see the tutorial.

Instances4HasForeign, HasLink, MkLink, Foreign
datadata WithResource (res :: k)
#
Instances4HasForeign, HasLink, MkLink, Foreign
datadata HttpVersion
#

HTTP Version.

Note that the Show instance is intended merely for debugging.

Instances10Eq, Data, Ord, Show, Generic, HasForeign, …
datadata Summary (sym :: Symbol)
#

Add a short summary for (part of) API.

Example:

Example1 expression
type MyApi = Summary "Get book by ISBN." :> "books" :> Capture "isbn" Text :> Get '[JSON] Book
Instances4HasForeign, HasLink, MkLink, Foreign
datadata Description (sym :: Symbol)
#

Add more verbose description for (part of) API.

Example:

Example1 expression
:{type MyApi = Description "This comment is visible in multiple Servant interpretations \ \and can be really long if necessary. \ \Haskell multiline String support is not perfect \ \but it's still very readable.":> Get '[JSON] Book:}
Instances4HasForeign, HasLink, MkLink, Foreign
datadata NamedRoutes (api :: Type -> Type)
#

Combinator for embedding a record of named routes into a Servant API type.

Instances4HasForeign, HasLink, MkLink, Foreign
datadata Strict
#

Strictly parsed argument. Not wrapped.

typetype Header = Header' '[Optional, Strict]
#

Extract the given header's value as a value of type a. I.e. header sent by client, parsed by server.

Example:

Example4 expressions
newtype Referer = Referer Text deriving (Eq, Show)           -- GET /view-my-referertype MyApi = "view-my-referer" :> Header "from" Referer :> Get '[JSON] Referer
datadata ResponseHeader (sym :: Symbol) a
#
Instances4Functor, Eq, Show, NFData
datadata StdMethod
#

HTTP standard method (as defined by RFC 2616, and PATCH which is defined by RFC 5789).

Instances19Bounded, Enum, Eq, Data, Ord, Read, …
datadata BasicAuth (realm :: Symbol) userData
#

Combinator for Basic Access Authentication.

  • IMPORTANT*: Only use Basic Auth over HTTPS! Credentials are not hashed or encrypted. Note also that because the same credentials are sent on every request, Basic Auth is not as secure as some alternatives. Further, the implementation in servant-server does not protect against some types of timing attacks.

In Basic Auth, username and password are base64-encoded and transmitted via the Authorization header. Handshakes are not required, making it relatively efficient.

Instances2HasLink, MkLink
typetype Capture = Capture' '[]
#

Capture a value from the request path under a certain type a.

Example:

Example2 expressions
-- GET /books/:isbntype MyApi = "books" :> Capture "isbn" Text :> Get '[JSON] Book
classclass Accept (ctype :: k) where
#

Instances of Accept represent mimetypes. They are used for matching against the Accept HTTP header of the request, and for setting the Content-Type header of the response

Example:

Example3 expressions
import Network.HTTP.Media ((//), (/:))data HTML:{instance Accept HTML where   contentType _ = "text" // "html" /: ("charset", "utf-8"):}
Instances4Accept
  • Accept FormUrlEncodedDefined in servant-0.20.2 · Servant.API.ContentTypes
    application/x-www-form-urlencoded
  • Accept JSONDefined in servant-0.20.2 · Servant.API.ContentTypes
    application/json
  • Accept OctetStreamDefined in servant-0.20.2 · Servant.API.ContentTypes
    application/octet-stream
  • Accept PlainTextDefined in servant-0.20.2 · Servant.API.ContentTypes
    text/plain;charset=utf-8
datadata FormUrlEncoded
#
Instances5Accept, MimeRender, MimeUnrender
classclass Accept ctype => MimeRender (ctype :: k) a where
#

Instantiate this class to register a way of serializing a type based on the Accept header.

Example:

data MyContentType

instance Accept MyContentType where
   contentType _ = "example" // "prs.me.mine" /: ("charset", "utf-8")

instance Show a => MimeRender MyContentType a where
   mimeRender _ val = pack ("This is MINE! " ++ show val)

type MyAPI = "path" :> Get '[MyContentType] Int

Methods

Instances11MimeRender, …
classclass Accept ctype => MimeUnrender (ctype :: k) a where
#

Instantiate this class to register a way of deserializing a type based on the request's Content-Type header.

Example3 expressions
import Network.HTTP.Media hiding (Accept)import qualified Data.ByteString.Lazy.Char8 as BSCdata MyContentType = MyContentType String
Example1 expression
:{instance Accept MyContentType where   contentType _ = "example" // "prs.me.mine" /: ("charset", "utf-8"):}
Example1 expression
:{instance Read a => MimeUnrender MyContentType a where   mimeUnrender _ bs = case BSC.take 12 bs of     "MyContentType" -> return . read . BSC.unpack $ BSC.drop 12 bs     _ -> Left "didn't start with the magic incantation":}
Example1 expression
type MyAPI = "path" :> ReqBody '[MyContentType] Int :> Get '[JSON] Int

Methods

Instances11MimeUnrender, …
datadata OctetStream
#
Instances7Accept, MimeRender, MimeUnrender, …
datadata PlainText
#
Instances9Accept, MimeRender, MimeUnrender, …
datadata AuthProtect (tag :: k)
#

A generalized Authentication combinator. Use this if you have a non-standard authentication technique.

NOTE: THIS API IS EXPERIMENTAL AND SUBJECT TO CHANGE.

Instances2HasLink, MkLink
classclass GenericMode (mode :: k) where
#

A class with a type family that applies an appropriate type family to the api parameter. For example, AsApi will leave api untouched, while AsServerT m will produce ServerT api m.

Associated types

  • type family (:-) (mode :: k) api
Instances2GenericMode
familytype family (:-) (mode :: k) api
#
Instances2:-
  • type (:-) AsApi api = apiDefined in servant-0.20.2 · Servant.API.Generic
  • type (:-) (AsLink a) api = MkLink api aDefined in servant-0.20.2 · Servant.Links
datadata AsApi
#

A type that specifies that an API record contains an API definition. Only useful at type-level.

Instances2GenericMode, :-
  • GenericMode AsApiDefined in servant-0.20.2 · Servant.API.Generic
  • type (:-) AsApi api = apiDefined in servant-0.20.2 · Servant.API.Generic
typetype ToServant (routes :: k -> Type) (mode :: k) = GToServant (Rep (routes mode))
#

Turns a generic product type into a tree of :<|> combinators.

valuefromServant
  1. :: GenericServant routes mode
  2. => ToServant routes mode
  3. -> routes mode
#

Inverse of toServant.

This can be used to turn generated values such as client functions into records.

You may need to provide a type signature for the output type (your record type).

datadata Lenient
#

Leniently parsed argument, i.e. parsing never fail. Wrapped in Either Text.

datadata Required
#

Required argument. Not wrapped.

Lookup the value associated to the sym query string parameter and try to extract it as a value of type a.

Example:

Example2 expressions
-- /books?author=<author name>type MyApi = "books" :> QueryParam "author" Text :> Get '[JSON] [Book]
datadata DeepQuery (sym :: Symbol) a
#

Extract an deep object from a query string.

Example:

Example2 expressions
-- /books?filter[author][name]=<author name>&filter[year]=<book year>type MyApi = "books" :> DeepQuery "filter" BookQuery :> Get '[JSON] [Book]
datadata QueryString
#

Extract the whole query string from a request. This is useful for query strings containing dynamic parameter names. For query strings with static parameter names, QueryParam is more suited.

Example:

Example2 expressions
-- /books?author=<author name>&year=<book year>type MyApi = "books" :> QueryString :> Get '[JSON] [Book]
datadata RawM
#

Variant of Raw that lets you access the underlying monadic context to process the request.

Instances2HasLink, MkLink
  • HasLink RawMDefined in servant-0.20.2 · Servant.Links
  • type MkLink RawM a = aDefined in servant-0.20.2 · Servant.Links
typetype ReqBody = ReqBody' '[Required, Strict]
#

Extract the request body as a value of type a.

Example:

Example2 expressions
-- POST /bookstype MyApi = "books" :> ReqBody '[JSON] Book :> Post '[JSON] Book
classclass AddHeader (mods :: [Type]) (h :: Symbol) v orig new | mods h v orig -> new, new -> mods, new -> h, new -> v, new -> orig where
#
Instances4AddHeader
datadata Headers (ls :: [Type]) a
#

Response Header objects. You should never need to construct one directly. Instead, use addOptionalHeader.

Constructors

Instances6AddHeader, Functor, NFData, GetHeaders, HasStatus, StatusOf
valueaddHeader :: AddHeader '[Optional, Strict] h v orig new => v -> orig -> new
#

addHeader adds a header to a response. Note that it changes the type of the value in the following ways:

  1. A simple value is wrapped in "Headers '[hdr]":

Example2 expressions
let example0 = addHeader 5 "hi" :: Headers '[Header "someheader" Int] String;getHeaders example0[("someheader","5")]
  1. A value that already has a header has its new header *prepended* to the existing list:

Example3 expressions
let example1 = addHeader 5 "hi" :: Headers '[Header "someheader" Int] String;let example2 = addHeader True example1 :: Headers '[Header "1st" Bool, Header "someheader" Int] StringgetHeaders example2[("1st","true"),("someheader","5")]

Note that while in your handlers type annotations are not required, since the type can be inferred from the API type, in other cases you may find yourself needing to add annotations.

valuelookupResponseHeader
  1. :: HasResponseHeader h a headers
  2. => Headers headers r
  3. -> ResponseHeader h a
#

Look up a specific ResponseHeader, without having to know what position it is in the HList.

Example3 expressions
let example1 = addHeader 5 "hi" :: Headers '[Header "someheader" Int] Stringlet example2 = addHeader True example1 :: Headers '[Header "1st" Bool, Header "someheader" Int] StringlookupResponseHeader example2 :: ResponseHeader "someheader" IntHeader 5
Example1 expression
lookupResponseHeader example2 :: ResponseHeader "1st" BoolHeader True

Usage of this function relies on an explicit type annotation of the header to be looked up. This can be done with type annotations on the result, or with an explicit type application. In this example, the type of header value is determined by the type-inference, we only specify the name of the header:

Example2 expressions
:set -XTypeApplicationscase lookupResponseHeader @"1st" example2 of { Header b -> b ; _ -> False }True
valuenoHeader :: AddHeader '[Optional, Strict] h v orig new => orig -> new
#

Deliberately do not add a header to a value.

Example2 expressions
let example1 = noHeader "hi" :: Headers '[Header "someheader" Int] StringgetHeaders example1[]
classclass FramingRender (strategy :: k) where
#

The FramingRender class provides the logic for emitting a framing strategy. The strategy transforms a SourceT m a into SourceT m ByteString, therefore it can prepend, append and intercalate framing structure around chunks.

Note: as the Monad m is generic, this is pure transformation.

Methods

Instances3FramingRender
classclass FramingUnrender (strategy :: k) where
#

The FramingUnrender class provides the logic for parsing a framing strategy.

Methods

Instances3FramingUnrender
classclass FromSourceIO chunk a | a -> chunk where
#

FromSourceIO is intended to be implemented for types such as Conduit, Pipe, etc. By implementing this class, all such streaming abstractions can be used directly on the client side for talking to streaming endpoints.

Methods

Instances1FromSourceIO
datadata NetstringFraming
#

The netstring framing strategy as defined by djb: http://cr.yp.to/proto/netstrings.txt

Any string of 8-bit bytes may be encoded as [len]":"[string]",". Here [string] is the string and [len] is a nonempty sequence of ASCII digits giving the length of [string] in decimal. The ASCII digits are 30 for 0, 31 for 1, and so on up through 39 for 9. Extra zeros at the front of [len] are prohibited: [len] begins with 30 exactly when [string] is empty.

For example, the string "hello world!" is encoded as 32 3a 68 65 6c 6c 6f 20 77 6f 72 6c 64 21 2c, i.e., "12:hello world!,". The empty string is encoded as "0:,".

Instances2FramingRender, FramingUnrender
datadata NewlineFraming
#

A simple framing strategy that has no header, and inserts a newline character after each frame. This assumes that it is used with a Content-Type that encodes without newlines (e.g. JSON).

Instances2FramingRender, FramingUnrender
datadata NoFraming
#

A framing strategy that does not do any framing at all, it just passes the input data This will be used most of the time with binary data, such as files

Instances2FramingRender, FramingUnrender
  • FramingRender NoFramingDefined in servant-0.20.2 · Servant.API.Stream
  • FramingUnrender NoFramingDefined in servant-0.20.2 · Servant.API.Stream

    As NoFraming doesn't have frame separators, we take the chunks as given and try to convert them one by one.

    That works well when a is a ByteString.

typetype SourceIO = SourceT IO
#

Stream endpoints may be implemented as producing a SourceIO chunk.

Clients reading from streaming endpoints can be implemented as consuming a SourceIO chunk.

classclass ToSourceIO chunk a | a -> chunk where
#

ToSourceIO is intended to be implemented for types such as Conduit, Pipe, etc. By implementing this class, all such streaming abstractions can be used directly as endpoints.

Methods

Instances3ToSourceIO
familytype family IsElem endpoint api :: Constraint where
#

Closed type family, check if endpoint is within api. Uses IsElem' if it exhausts all other options.

Example1 expression
ok (Proxy :: Proxy (IsElem ("hello" :> Get '[JSON] Int) SampleAPI))OK
Example1 expression
ok (Proxy :: Proxy (IsElem ("bye" :> Get '[JSON] Int) SampleAPI))...... Could not ......

An endpoint is considered within an api even if it is missing combinators that don't affect the URL:

Example1 expression
ok (Proxy :: Proxy (IsElem (Get '[JSON] Int) (Header "h" Bool :> Get '[JSON] Int)))OK
Example1 expression
ok (Proxy :: Proxy (IsElem (Get '[JSON] Int) (ReqBody '[JSON] Bool :> Get '[JSON] Int)))OK
  • N.B.:* IsElem a b can be seen as capturing the notion of whether the URL represented by a would match the URL represented by b, *not* whether a request represented by a matches the endpoints serving b (for the latter, use IsIn).

Equations

familytype family IsElem' a s :: Constraint
#

You may use this type family to tell the type checker that your custom type may be skipped as part of a link. This is useful for things like QueryParam that are optional in a URI and do not affect them if they are omitted.

Example2 expressions
data CustomThingtype instance IsElem' e (CustomThing :> s) = IsElem e s

Note that IsElem is called, which will mutually recurse back to IsElem' if it exhausts all other options again.

Once you have written a HasLink instance for CustomThing you are ready to go.

classclass KnownStatus (StatusOf a) => HasStatus a where
#

Associated types

Instances3HasStatus
  • HasStatus NoContentDefined in servant-0.20.2 · Servant.API.UVerb

    If an API can respond with NoContent we assume that this will happen with the status code 204 No Content. If this needs to be overridden, WithStatus can be used.

  • KnownStatus n => HasStatus (WithStatus n a)Defined in servant-0.20.2 · Servant.API.UVerb

    an instance of this typeclass assigns a HTTP status code to a return type

    Example:

       data NotFoundError = NotFoundError String
    
       instance HasStatus NotFoundError where
         type StatusOf NotFoundError = 404
    

    You can also use the convience newtype wrapper WithStatus if you want to avoid writing a HasStatus instance manually. It also has the benefit of showing the status code in the type; which might aid in readability.

  • HasStatus a => HasStatus (Headers ls a)Defined in servant-0.20.2 · Servant.API.UVerb
familytype family Statuses (as :: [Type]) :: [Nat]
#
Instances2Statuses
  • type Statuses '[] = '[]Defined in servant-0.20.2 · Servant.API.UVerb
  • type Statuses (a ': as) = StatusOf a ': Statuses asDefined in servant-0.20.2 · Servant.API.UVerb
familytype family Statuses (as :: [Type]) :: [Nat]
#
Instances2Statuses
  • type Statuses '[] = '[]Defined in servant-0.20.2 · Servant.API.UVerb
  • type Statuses (a ': as) = StatusOf a ': Statuses asDefined in servant-0.20.2 · Servant.API.UVerb
datadata UVerb (method :: StdMethod) (contentTypes :: [Type]) (as :: [Type])
#

A variant of Verb that can have any of a number of response values and status codes.

FUTUREWORK: it would be nice to make Verb a special case of UVerb, and only write instances for HasServer etc. for the latter, getting them for the former for free. Something like:

type Verb method statusCode contentTypes a = UVerb method contentTypes [WithStatus statusCode a]

Backwards compatibility is tricky, though: this type alias would mean people would have to use respond instead of pure or return, so all old handlers would have to be rewritten.

Instances3HasLink, AtMostOneFragment, MkLink
newtypenewtype WithStatus (k :: Nat) a
#

A simple newtype wrapper that pairs a type with its status code. It implements all the content types that Servant ships with by default.

Constructors

Instances12MimeRender, MimeUnrender, Eq, Show, HasStatus, StatusOf, …
typetype IsMember (a :: u) (as :: [u]) = (Unique as, CheckElemIsMember a as, UElem a as)
#
familytype family Unique (xs :: [k]) :: Constraint where
#

Check whether all values in a type-level list are distinct. This will throw a nice error if there are any duplicate elements in the list.

Equations

familytype family If (cond :: Bool) (tru :: k) (fls :: k) :: k where
#

Type-level If. If True a b ==> a; If False a b ==> b

Equations

classclass FromHttpApiData a where
#

Parse value from HTTP API data.

WARNING: Do not derive this using DeriveAnyClass as the generated instance will loop indefinitely.

Methods

Instances53FromHttpApiData, …
classclass ToHttpApiData a where
#

Convert value to HTTP API data.

WARNING: Do not derive this using DeriveAnyClass as the generated instance will loop indefinitely.

Methods

Instances53ToHttpApiData, …
  • ToHttpApiData SetCookieDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData

    Note: this instance works correctly for alphanumeric name and value

    Example2 expressions
    let Right c = parseUrlPiece "SESSID=r2t5uvjq435r4q7ib3vtdjq120" :: Either Text SetCookietoUrlPiece c"SESSID=r2t5uvjq435r4q7ib3vtdjq120"
    Example1 expression
    toHeader c"SESSID=r2t5uvjq435r4q7ib3vtdjq120"
  • ToHttpApiData IntegerDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData NaturalDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData StringDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData VoidDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData AllDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData AnyDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData VersionDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece (Version [1, 2, 3] [])"1.2.3"
  • ToHttpApiData Int16Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData Int32Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData Int64Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData Int8Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData Word16Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData Word32Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData Word64Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData Word8Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData BoolDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData CharDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData DoubleDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData FloatDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData IntDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData OrderingDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData WordDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData LinkDefined in servant-0.20.2 · Servant.Links
  • ToHttpApiData TextDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData TextDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData DayDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece (fromGregorian 2015 10 03)"2015-10-03"
  • ToHttpApiData MonthDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example2 expressions
    import Data.Time.Calendar.Month.Compat (Month (..))MkMonth 244822040-03
    Example1 expression
    toUrlPiece $ MkMonth 24482"2040-03"
  • ToHttpApiData QuarterDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example2 expressions
    import Data.Time.Calendar.Quarter.Compat (Quarter (..))MkQuarter 80402010-Q1
    Example1 expression
    toUrlPiece $ MkQuarter 8040"2010-q1"
  • ToHttpApiData QuarterOfYearDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece Q4"q4"
  • ToHttpApiData DayOfWeekDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece Monday"monday"
  • ToHttpApiData NominalDiffTimeDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData UTCTimeDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece $ UTCTime (fromGregorian 2015 10 03) 864.5"2015-10-03T00:14:24.500Z"
  • ToHttpApiData LocalTimeDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece $ LocalTime (fromGregorian 2015 10 03) (TimeOfDay 14 55 21.687)"2015-10-03T14:55:21.687"
  • ToHttpApiData TimeOfDayDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece $ TimeOfDay 14 55 23.1"14:55:23.100"
  • ToHttpApiData ZonedTimeDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece $ ZonedTime (LocalTime (fromGregorian 2015 10 03) (TimeOfDay 14 55 51.001)) utc"2015-10-03T14:55:51.001Z"
    Example1 expression
    toUrlPiece $ ZonedTime (LocalTime (fromGregorian 2015 10 03) (TimeOfDay 14 55 51.001)) (TimeZone 120 True "EET")"2015-10-03T14:55:51.001+02:00"
  • ToHttpApiData UUIDDefined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData ()Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece ()"_"
  • ToHttpApiData a => ToHttpApiData (First a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData a => ToHttpApiData (Last a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData a => ToHttpApiData (Max a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData a => ToHttpApiData (Min a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData a => ToHttpApiData (Identity a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData a => ToHttpApiData (First a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData a => ToHttpApiData (Last a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData a => ToHttpApiData (Dual a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData a => ToHttpApiData (Product a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData a => ToHttpApiData (Sum a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData a => ToHttpApiData (Maybe a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece (Just "Hello")"just Hello"
  • HasResolution a => ToHttpApiData (Fixed a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData

    Note: this instance is not polykinded

  • (ToHttpApiData a, ToHttpApiData b) => ToHttpApiData (Either a b)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
    Example2 expressions
    toUrlPiece (Left "err" :: Either String Int)"left err"toUrlPiece (Right 3 :: Either String Int)"right 3"
  • ToHttpApiData a => ToHttpApiData (Const a b)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData
  • ToHttpApiData a => ToHttpApiData (Tagged b a)Defined in http-api-data-0.6.1 · Web.Internal.HttpApiData

    Note: this instance is not polykinded

datadata URI
#

Represents a general universal resource identifier using its component parts.

For example, for the URI

  foo://anonymous@www.haskell.org:42/ghc?query#frag

the components are:

Constructors

Instances12Eq, Data, Ord, Show, Generic, NFData, …
datadata SBool (b :: Bool) where
#

Constructors

Instances12EqP, GCompare, GEq, GNFData, GRead, GShow, …
  • EqP SBoolDefined in singleton-bool-0.1.8 · Data.Singletons.Bool
  • GCompare SBoolDefined in singleton-bool-0.1.8 · Data.Singletons.Bool
  • GEq SBoolDefined in singleton-bool-0.1.8 · Data.Singletons.Bool
    Example1 expression
    geq STrue STrueJust Refl
    Example1 expression
    geq STrue SFalseNothing
  • GNFData SBoolDefined in singleton-bool-0.1.8 · Data.Singletons.Bool
  • GRead SBoolDefined in singleton-bool-0.1.8 · Data.Singletons.Bool
    Example1 expression
    readsPrec 0 "Some STrue" :: [(Some SBool, String)][(Some STrue,"")]
    Example1 expression
    readsPrec 0 "Some SFalse" :: [(Some SBool, String)][(Some SFalse,"")]
    Example1 expression
    readsPrec 0 "Some Else" :: [(Some SBool, String)][]
  • GShow SBoolDefined in singleton-bool-0.1.8 · Data.Singletons.Bool
    Example1 expression
    showsPrec 0 STrue """STrue"
  • OrdP SBoolDefined in singleton-bool-0.1.8 · Data.Singletons.Bool
  • Eq (SBool b)Defined in singleton-bool-0.1.8 · Data.Singletons.Bool
  • Ord (SBool b)Defined in singleton-bool-0.1.8 · Data.Singletons.Bool
  • Show (SBool b)Defined in singleton-bool-0.1.8 · Data.Singletons.Bool
  • NFData (SBool b)Defined in singleton-bool-0.1.8 · Data.Singletons.Bool
  • SBoolI b => Boring (SBool b)Defined in singleton-bool-0.1.8 · Data.Singletons.Bool
classclass SBoolI (b :: Bool) where
#

Methods

Instances2SBoolI
  • SBoolI 'FalseDefined in singleton-bool-0.1.8 · Data.Singletons.Bool
  • SBoolI 'TrueDefined in singleton-bool-0.1.8 · Data.Singletons.Bool