An application programming interface (API) defines how software components communicate. A web API exposes named HTTP endpoints, their request methods, and the data they accept or return. A todo-list API, for example, sends JSON between a server and a command-line client. section 16.1 section 17.1
A CRUD API organizes operations for creating, reading, updating, and deleting data. The same pattern can support questionnaire services, appointment planners, booking platforms, and store backends. section 16.1
A typesafe API can specify these details before its server implementation:
- Routes and HTTP verbs, such as GET, POST, PATCH, and DELETE. section 17.1.1
- Response formats and types, such as a JSON-encoded value or no-content response. section 17.1.1
- Request bodies and captured path values, with invalid request bodies rejected automatically. section 17.1.1
- Multiple endpoints combined into one API definition. section 17.1.1
A todo-list API
A single API type can declare an entries route that returns todo entries, an add route that accepts a JSON TodoEntry and returns its identifier, and a toggle route that captures an integer identifier. In Servant, :> extends one endpoint description, while :<|> joins endpoint descriptions. 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
This declaration collects the read, add, and toggle operations of a todo-list service in one type. section 17.1.1
Keeping the machine-facing API separate from a human-facing HTML page can simplify generated clients: a middleware wrapper can handle the root page while other requests continue to the API server. Servant can also derive client functions from the API definition. section 17.2.2 section 17.4











































