Leanpub Header

Skip to main content

Building Web Applications with Servant in Haskell

A Practical Guide to Type-Safe APIs from Design to Deployment

Building Web Applications with Servant in Haskell
This book is 100% completeLast updated on 2026-08-28

Build robust web applications and REST APIs with Haskell and Servant. This practical guide takes you from core Haskell concepts to type-safe API design, PostgreSQL, JWT authentication, testing and deployment. Along the way, you’ll build a complete versioned API using patterns that make real-world Servant projects reliable and maintainable.

Minimum price

$19.00

$29.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
EPUB
WEB
APP
153
Pages
About

About

About the Book

This book teaches you how to build production-quality web applications and REST APIs using the Servant framework in Haskell. Starting from foundational Haskell concepts, it guides you through type-level API design, database integration, authentication, testing, and deployment. By the end, you will have built a complete versioned REST API with PostgreSQL persistence, JWT authentication, structured error handling, automated tests, and Docker configuration that demonstrates all the patterns used in real-world Servant applications.

Author

About the Author

Steve Publications

Steve is a technology professional with more than 20 years of experience in software development, server infrastructure, cybersecurity, vulnerability research and reverse engineering. Throughout his career, he has designed, secured, analyzed and tested complex software and infrastructure, with a particular focus on understanding how systems fail and how they can be made more secure.

Outside of work, Steve enjoys sharing knowledge with the technology community. He collaborates with researchers, industry experts and technology professionals to write practical books covering software development, cybersecurity, cloud computing, networking, DevOps, artificial intelligence and enterprise technologies. His books focus on practical learning through clear explanations, real-world examples and hands-on exercises. With more than two decades of industry experience, his goal is to help IT professionals, students and technology enthusiasts build useful skills and stay current in a rapidly changing industry.

We believe readers deserve to know how our books are created. Most of our authors are not native English speakers, so we use AI to help translate, proofread manuscripts, fix grammar, improve sentence structure and make technical explanations easier to read. AI is used as an editing tool only. It does not replace the research, technical knowledge or hands-on experience behind our books. Some of our authors also prefer to remain anonymous for privacy or professional reasons. In those cases, we publish their work under a different name. The author's name may be different, but the quality of the content and our review process remain the same.

Every book is written, reviewed and maintained by experienced technology professionals, with contributions from our private technical community of more than 420 engineers and researchers. We spend far more time validating technical accuracy and keeping our content up to date than generating text. We are always interested in working with experienced professionals who have deep expertise in a particular technology or domain. If you would like to publish a book with us or help review an existing manuscript, we'd love to hear from you. Send us a message describing your area of expertise. We are especially interested in niche technologies, specialized skills and emerging topics that are underrepresented in existing technical literature.

If you look through the contents of our books, you'll see practical examples, detailed explanations and material that is regularly updated. Our goal is to publish books that professionals can actually rely on, not low-effort AI-generated content. If you ever feel that one of our books does not meet that standard, Leanpub offers a 60-day money-back guarantee. Feel free to request a refund if you are not satisfied with your purchase.

Contents

Table of Contents

A Practical Guide to Type-Safe APIs from Design to Deployment

Introduction

Chapter 1: The Haskell Web Ecosystem and Servant’s Philosophy

  1. The Landscape of Haskell Web Frameworks
  2. What Makes Servant Different
  3. Type-Level API Descriptions as Single Source of Truth
  4. How Servant Splits Its Responsibilities Across Packages
  5. When to Choose Servant and When Not To

Chapter 2: Getting Started with Haskell and Your Development Environment

  1. Installing GHC and Choosing a Version
  2. Build Tools: Cabal versus Stack in Modern Practice
  3. Your First Haskell Project Structure
  4. Essential Development Tooling and Extensions
  5. Compiling, Running, and Debugging Basics

Chapter 3: The Haskell Foundations You Need for Servant

  1. Types, Type Inference, and Algebraic Data Types
  2. Functions, Partial Application, and Currying
  3. Type Classes: Polymorphism with Structure
  4. The Maybe and Either Types for Error Handling
  5. Monads: Chaining Computations with Context
  6. Monad Transformers: Layering Effects

Chapter 4: Your First Servant API

  1. Defining Your First Type-Level API Route
  2. The Handler Monad and Returning Responses
  3. Serving Your API with Warp
  4. Testing Endpoints with curl and HTTP Clients
  5. Understanding How Servant Routes Requests to Handlers

Chapter 5: Deep Dive into Servant Combinators

  1. HTTP Methods: Get, Post, Put, Patch, Delete
  2. Path Parameters with Capture and CaptureAll
  3. Query Parameters: Single, Multiple, and Flags
  4. Request Bodies with ReqBody
  5. Response Types, Status Codes, and Content Types
  6. Combining Routes with the Left Alternation Operator

Chapter 6: JSON Serialization with Aeson

  1. The Aeson Ecosystem: ToJSON, FromJSON, and Value
  2. Manual Instance Derivation for Full Control
  3. Automatic Deriving with Generic
  4. Custom Serialization Logic
  5. Handling Partial Updates and Optional Fields
  6. Common JSON Pitfalls in Servant Applications

Chapter 7: API Composition and Modular Design

  1. Composing APIs with the Alternation Operator
  2. Nested Routes and Sub-APIs
  3. Reusable API Type Components
  4. Versioning Strategies for Evolving APIs
  5. Custom Servant Combinators
  6. Module Organization for Large Projects

Chapter 8: Application Environments and Dependency Injection

  1. The Problem of Global State in Web Applications
  2. ReaderT as an Environment Layer
  3. Designing Your Application Environment Record
  4. hoistServer: Adapting Handler Monads
  5. Configuration Management Across Environments
  6. Dependency Injection Patterns in Servant

Chapter 9: Error Handling, Validation, and Logging

  1. Servant’s Structured Error System
  2. Custom Error Types and Status Codes
  3. Input Validation Patterns
  4. Logging with Middleware
  5. Request IDs and Traceability
  6. Exception Handling in Handlers

Chapter 10: Persistence with PostgreSQL

  1. Choosing a Database Library: postgresql-simple versus Others
  2. Connection Pooling with resource-pool
  3. Transactions and Isolation Levels
  4. Database Migrations with migrate
  5. Repository Layer Design
  6. Mapping Between Database and Domain Models

Chapter 11: Authentication and Authorization

  1. Security Fundamentals for Web APIs
  2. Password Hashing with Argon2 or bcrypt
  3. JWT-Based Token Authentication
  4. Session and Cookie-Based Authentication
  5. Authorization: Roles, Permissions, and Policies
  6. Protecting Specific Endpoints with Servant Combinators

Chapter 12: Building the Reference Application

  1. Application Architecture Overview
  2. Directory Structure and Module Layout
  3. Domain Models and Database Schema
  4. The Complete API Definition
  5. Handler Implementations
  6. Configuration and Application Bootstrap

Chapter 13: Clients, Documentation, and External Services

  1. Generated Servant Clients
  2. Handwritten Client Implementations
  3. Calling External APIs from Your Server
  4. OpenAPI and Swagger Documentation Generation
  5. Serving Interactive API Documentation

Chapter 14: Testing Your Servant Application

  1. Unit Testing Handlers in Isolation
  2. Property-Based Testing with QuickCheck
  3. Integration Tests Against a Running Server
  4. Test Databases and Schema Management
  5. Mocking External Dependencies
  6. Organizing Your Test Suite

Chapter 15: Middleware, CORS, and Cross-Cutting Concerns

  1. WAI Middleware Architecture
  2. Handling CORS Properly
  3. Compression and Performance Middleware
  4. Timeouts and Rate Limiting
  5. Custom Middleware for Logging and Metrics
  6. Ordering and Composing Middleware

Chapter 16: Observability, Performance, and Production Operations

  1. Metrics Collection and Monitoring
  2. Distributed Tracing Integration
  3. Profiling Haskell Web Applications
  4. Caching Strategies
  5. Concurrency and Resource Limits
  6. Graceful Shutdown and Reloading

Chapter 17: Deployment and DevOps

  1. Containerizing with Docker
  2. Multi-Stage Builds for Small Images
  3. Reverse Proxies: Nginx and Traefik
  4. HTTPS Termination
  5. CI/CD Pipelines with GitHub Actions or GitLab CI
  6. Configuration Management in Production

Conclusion: The Servant Way Forward

References

  1. Servant Core Documentation and Packages
  2. Authentication and Authorization
  3. JSON Serialization
  4. Web Server and WAI
  5. Database Integration
  6. OpenAPI and Documentation
  7. Testing
  8. Build Tools and Tooling
  9. GHC and Haskell Language
  10. External Articles and Tutorials
  11. Academic Papers
  12. Version Information Summary

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $15 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub