Testing Servant APIs in Haskell: wai-extra, hspec-wai, and Integration Tests

Testing Servant APIs in Haskell: wai-extra, hspec-wai, and Integration Tests

Servant is a type-level web framework for Haskell where API types are defined as type-level combinators. Testing Servant APIs uses wai-extra for HTTP simulation and hspec-wai for a DSL that makes request/response assertions readable.

Setup

test-suite api-tests
  build-depends:
    , base
    , servant-server
    , hspec
    , hspec-wai
    , hspec-wai-json
    , wai
    , wai-extra
    , aeson
    , my-app

A Simple API to Test

-- src/API.hs
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
module API where

import Servant
import Data.Aeson
import GHC.Generics

data User = User
  { userId   :: Int
  , userName :: String
  , userEmail :: String
  } deriving (Show, Eq, Generic, ToJSON, FromJSON)

data NewUser = NewUser
  { newUserName  :: String
  , newUserEmail :: String
  } deriving (Show, Eq, Generic, ToJSON, FromJSON)

type UserAPI =
       "users" :> Get '[JSON] [User]
  :<|> "users" :> ReqBody '[JSON] NewUser :> Post '[JSON] User
  :<|> "users" :> Capture "id" Int :> Get '[JSON] User
  :<|> "users" :> Capture "id" Int :> Delete '[JSON] NoContent

userServer :: IORef [User] -> IORef Int -> Server UserAPI
userServer usersRef nextIdRef =
  getUsers :<|> createUser :<|> getUser :<|> deleteUser
  where
    getUsers = liftIO $ readIORef usersRef
    
    createUser newUser = liftIO $ do
      uid <- readIORef nextIdRef
      let user = User uid (newUserName newUser) (newUserEmail newUser)
      modifyIORef usersRef (user:)
      modifyIORef nextIdRef (+1)
      return user
    
    getUser uid = do
      users <- liftIO $ readIORef usersRef
      case find ((== uid) . userId) users of
        Just user -> return user
        Nothing   -> throwError err404 { errBody = "User not found" }
    
    deleteUser uid = do
      liftIO $ modifyIORef usersRef (filter ((/= uid) . userId))
      return NoContent

makeApp :: IO Application
makeApp = do
  usersRef <- newIORef []
  nextIdRef <- newIORef 1
  return $ serve (Proxy :: Proxy UserAPI) (userServer usersRef nextIdRef)

Basic hspec-wai Tests

-- test/APISpec.hs
module APISpec (spec) where

import Test.Hspec
import Test.Hspec.Wai
import Test.Hspec.Wai.JSON
import Network.HTTP.Types
import API

spec :: Spec
spec = with makeApp $ do
  describe "GET /users" $ do
    it "returns 200 and empty list initially" $ do
      get "/users" `shouldRespondWith` [json|[]|] { matchStatus = 200 }

    it "returns Content-Type application/json" $ do
      get "/users" `shouldRespondWith` 200
        { matchHeaders = ["Content-Type" <:> "application/json;charset=utf-8"] }

  describe "POST /users" $ do
    it "creates a user and returns 200" $ do
      let body = [json|{ "newUserName": "Alice", "newUserEmail": "alice@example.com" }|]
      postJSON "/users" body `shouldRespondWith` 200

    it "returns created user with ID" $ do
      let body = [json|{ "newUserName": "Bob", "newUserEmail": "bob@example.com" }|]
      response <- postJSON "/users" body
      
      liftIO $ do
        let status = simpleStatus response
        status `shouldBe` ok200

  describe "GET /users/:id" $ do
    it "returns 404 for nonexistent user" $ do
      get "/users/999" `shouldRespondWith` 404

    it "returns user after creation" $ do
      -- Create user first
      let body = [json|{ "newUserName": "Carol", "newUserEmail": "carol@example.com" }|]
      postJSON "/users" body
      
      -- Fetch by ID
      get "/users/1" `shouldRespondWith` 200

  describe "DELETE /users/:id" $ do
    it "returns 200 after deletion" $ do
      let body = [json|{ "newUserName": "Dave", "newUserEmail": "dave@example.com" }|]
      postJSON "/users" body
      
      delete "/users/1" `shouldRespondWith` 200

    it "returns 404 after deletion" $ do
      let body = [json|{ "newUserName": "Eve", "newUserEmail": "eve@example.com" }|]
      postJSON "/users" body
      delete "/users/1"
      
      get "/users/1" `shouldRespondWith` 404

Custom Request Helpers

import Network.Wai.Test (SResponse)
import Test.Hspec.Wai

-- Helper for authenticated requests
authGet :: ByteString -> WaiSession st SResponse
authGet path =
  request methodGet path [("Authorization", "Bearer test-token")] ""

authPost :: ByteString -> LByteString -> WaiSession st SResponse
authPost path body =
  request methodPost path
    [ ("Content-Type", "application/json")
    , ("Authorization", "Bearer test-token")
    ] body

-- Usage
spec :: Spec
spec = with makeAuthApp $ do
  describe "Protected endpoints" $ do
    it "rejects unauthenticated requests" $ do
      get "/profile" `shouldRespondWith` 401

    it "allows authenticated requests" $ do
      authGet "/profile" `shouldRespondWith` 200

Testing Request Body Validation

describe "POST /users validation" $ do
  it "rejects missing name field" $ do
    let body = [json|{ "newUserEmail": "alice@example.com" }|]
    postJSON "/users" body `shouldRespondWith` 400

  it "rejects empty name" $ do
    let body = [json|{ "newUserName": "", "newUserEmail": "alice@example.com" }|]
    postJSON "/users" body `shouldRespondWith` 422

  it "rejects invalid email" $ do
    let body = [json|{ "newUserName": "Alice", "newUserEmail": "not-an-email" }|]
    postJSON "/users" body `shouldRespondWith` 422

Testing Response Body Structure

import Data.Aeson (decode)
import qualified Data.ByteString.Lazy as LBS

spec :: Spec
spec = with makeApp $ do
  describe "User response structure" $ do
    it "response includes all required fields" $ do
      let body = [json|{ "newUserName": "Alice", "newUserEmail": "alice@example.com" }|]
      response <- postJSON "/users" body
      
      liftIO $ do
        let mUser = decode (simpleBody response) :: Maybe Value
        case mUser of
          Nothing -> expectationFailure "Failed to decode response"
          Just user -> do
            user ^? key "userId" `shouldNotBe` Nothing
            user ^? key "userName" `shouldBe` Just (String "Alice")
            user ^? key "userEmail" `shouldBe` Just (String "alice@example.com")

Testing Pagination

type PagedAPI = "items" :> QueryParam "page" Int :> QueryParam "limit" Int :> Get '[JSON] PagedResponse

spec :: Spec
spec = with makeApp $ do
  describe "GET /items pagination" $ do
    it "defaults to page 1 with limit 20" $ do
      get "/items" `shouldRespondWith` 200

    it "respects page and limit parameters" $ do
      get "/items?page=2&limit=5" `shouldRespondWith` 200

    it "returns empty results for out-of-range page" $ do
      response <- get "/items?page=9999&limit=10"
      liftIO $ do
        let mPage = decode (simpleBody response) :: Maybe PagedResponse
        fmap items mPage `shouldBe` Just []

Integration Test with Real Database

For integration tests, use a test database with rollback:

import Database.PostgreSQL.Simple

spec :: Spec
spec = beforeAll setupTestDb $ afterAll teardownTestDb $ do
  describe "User API Integration" $ do
    it "creates and retrieves user" $ \conn -> do
      app <- makeAppWithDb conn
      flip runSession app $ do
        let body = [json|{ "newUserName": "Alice", "newUserEmail": "a@b.com" }|]
        postJSON "/users" body `shouldRespondWith` 200
        get "/users/1" `shouldRespondWith` 200

setupTestDb :: IO Connection
setupTestDb = do
  conn <- connect defaultConnectInfo { connectDatabase = "test_db" }
  execute_ conn "BEGIN"
  runMigrations conn
  return conn

teardownTestDb :: Connection -> IO ()
teardownTestDb conn = do
  execute_ conn "ROLLBACK"
  close conn

Error Response Testing

describe "Error responses" $ do
  it "404 includes descriptive message" $ do
    response <- get "/users/999"
    liftIO $ do
      simpleStatus response `shouldBe` notFound404
      -- Check error message in body
      let body = LBS.toStrict (simpleBody response)
      body `shouldContain` "User not found"

  it "400 includes validation errors" $ do
    let body = [json|{ "badField": "value" }|]
    response <- postJSON "/users" body
    liftIO $ do
      simpleStatus response `shouldBe` badRequest400

Conclusion

hspec-wai provides a clean DSL for HTTP testing that matches the clarity of Servant's type-level API definitions. The with combinator creates a fresh application state for each test group. Use request for full control over method, path, headers, and body. Combine with property tests that generate random valid and invalid inputs for thorough API coverage.

Read more

Start now free