liveBook · Manning

Type operator

As explained in Learn Haskell by Example

TypeOperators is a GHC language extension that permits operators in type-level syntax and declarations.

A type operator lets a type-level API description combine routing, request, and response information. Servant uses TypeOperators alongside DataKinds to build typed API definitions. section 17.1.1

Use Servant's operators to assemble endpoint descriptions:

  • Use (:>) to connect path segments and request or response details into one endpoint description. section 17.1.1
  • Use (:<|>) to combine multiple endpoint descriptions into one API. section 17.1.1 section 17.4
  • Combine operators with Get, PostCreated, PatchNoContent, ReqBody, Capture, and JSON to describe HTTP behavior and types. section 17.1.1

Todo API type

A todo API can combine an entries endpoint, an add endpoint accepting a TodoEntry request body, and a toggle endpoint capturing an integer identifier. The resulting type describes three endpoints in one API. section 17.1.1

Listing 17.1 A type for the todo list API server
{-# LANGUAGE TypeOperators #-}     #1
{-# LANGUAGE DataKinds #-}        #1
module Todos.Api where

import Servant.API
import Todos.Types

type TodoApi =
  "entries" :> Get '[JSON] [TodoEntry]        #2
    :<|> "add" :> ReqBody '[JSON] TodoEntry :>
 PostCreated '[JSON] Int                       #3
    :<|> "toggle" :> Capture "id" Int :> PatchNoContent    #4

Inspect the complete TodoApi declaration, including the required language extensions and each operator-based endpoint. section 17.1.1

How Learn Haskell by Example covers it

How deep it goes
Explains the two main operators through endpoint examples but stops short of their language-level internals.
Examples
Uses simple GET endpoints, combined endpoints, JSON responses, POST request bodies, and a todo-list API declaration.
What it assumes
Assumes basic Haskell module and type familiarity while teaching the required Servant operators through concrete API definitions.
What you can do after
Build typesafe Servant API declarations by composing endpoint descriptions with (:>) and (:<|>).
How it connects
Connects TypeOperators with DataKinds, Servant, HTTP verbs, JSON, request bodies, and captured path parameters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.