Servant (Haskell)

Servant is a Haskell library providing a type-level DSL for specifying web APIs.

Concepts

Verbs

Verbs describe endpoints: the request type (e.g. GET, POST, ...), status code, body type, etc.

Cookbook

URL captures

E.g., as in an endpoint /users/«user-name».

type API = "users" :> Capture "user-name" Text :> Get '[JSON] User

Authentication

See Servant-auth's docs.

Get JWT-Cookie and XSRF-TOKEN

  $ curl -H "Content-Type: application/json" \
    -d '{"name":"msyds","password":"password123"}' \
    -v http://localhost:8080/login

  ,* Host localhost:8080 was resolved.
  ,* IPv6: ::1
  ,* IPv4: 127.0.0.1
  ,*   Trying [::1]:8080...
  ,* connect to ::1 port 8080 from ::1 port 38734 failed: Connection refused
  ,*   Trying 127.0.0.1:8080...
  ,* Connected to localhost (127.0.0.1) port 8080
  ,* using HTTP/1.x
  > POST /login HTTP/1.1
  > Host: localhost:8080
  > User-Agent: curl/8.11.1
  > Accept: */*
  > Content-Type: application/json
  > Content-Length: 41
  > 
  ,* upload completely sent off: 41 bytes
  < HTTP/1.1 204 No Content
  < Date: Wed, 05 Mar 2025 19:32:35 GMT
  < Server: Warp/3.3.31
  < Content-Type: application/json;charset=utf-8
  < Set-Cookie: JWT-Cookie=eyJhbGciOiJIUzUxMiJ9.eyJkYXQiOnsibmFtZSI6Im1zeWRzIn19.5FusR3E9ObaKSrl9Ek_7ur5_s203cpOcF0y6GwIxMdXw1y2ypbRSZ-XAh3XFiapFrPjnLOuVLP5PqS_36yIncw; Path=/; HttpOnly; Secure; SameSite=Lax
  < Set-Cookie: XSRF-TOKEN=ZT+un9PXjV1XYW7RV4RCP3Z4rJ0qhfw5vNpmXyEhXQQ=; Path=/; Secure; SameSite=Lax
  < 
  ,* Connection #0 to host localhost left intact

Use for auth

  $ curl \
    -b "JWT-Cookie=«...»" \
    -b "XSRF-TOKEN=«...»" \
    -H "X-XSRF-TOKEN: «...»" \
    -v http://localhost:8080/protected-page

References