F# · Lesson 12

Designing an F# web API

Model the domain so illegal states can't be built, guard it with smart constructors and DTOs, validate in pipelines, carry errors as Result across layers to the right HTTP status, and wire dependencies as functions or with ASP.NET Core DI, in minimal APIs and Giraffe.

18 min read

In short

  • Model states as union cases, not flags
  • Private cases plus smart constructors: validate once
  • DTOs on the wire, domain types inside
  • One error union per workflow, mapped to HTTP at the edge
  • Dependencies as functions; DI at the edges

Why F# teams design backends this way

An F# backend on .NET runs on the same ASP.NET Core, the same cloud services and the same JSON as the C# services next to it. What changes is how the code inside is designed. The F# way puts most of the work into types:

  • The domain types make invalid data impossible to build, so most "is this valid?" checks happen once, at the edge.
  • Every workflow returns a Result whose error type lists exactly what can go wrong, so the HTTP layer can map each case to a status code, and the compiler tells you when a new case isn't handled.
  • Dependencies (database, clock, other services) are passed in as functions, so the business logic is testable without mocking libraries.

A request flows through the layers like this:

HTTP request
  -> request DTO          plain record, anything can be null or wrong
  -> validate             Result<Command, FieldError list>
  -> workflow             domain types only; I/O through functions passed in
  -> Result<Event, WorkflowError>
  -> response DTO / status code
HTTP response

This is often called functional core, imperative shell: pure decisions in the middle, I/O at the edges. A C# service has the same layers (controller, service, repository). The difference is how much the types guarantee.

Make illegal states unrepresentable

Here is an order the way it often starts, in TypeScript or C#:

▶ Try
interface Order {
  id: string;
  isPaid: boolean;
  paidAt?: Date;           // should be set when isPaid... hopefully
  trackingNumber?: string; // only for shipped orders... hopefully
  isCancelled: boolean;    // can a shipped order be cancelled? who knows
}

Nothing stops isPaid: false with a trackingNumber, or an order both shipped and cancelled. Every function has to re-check, and some forget. In F#, model the states instead of flags:

▶ Try
open System

type OrderState =
    | AwaitingPayment
    | Paid of paidAt: DateTimeOffset
    | Shipped of paidAt: DateTimeOffset * trackingNumber: string
    | Cancelled of reason: string

let describe (state: OrderState) : string =
    match state with
    | AwaitingPayment -> "waiting for payment"
    | Paid paidAt -> sprintf "paid on %s" (paidAt.ToString "yyyy-MM-dd")
    | Shipped(_, tracking) -> $"shipped, tracking {tracking}"
    | Cancelled reason -> $"cancelled: {reason}"

let ship (trackingNumber: string) (state: OrderState) : Result<OrderState, string> =
    match state with
    | Paid paidAt -> Ok(Shipped(paidAt, trackingNumber))
    | AwaitingPayment -> Error "an order must be paid before it ships"
    | Shipped _ -> Error "the order has already shipped"
    | Cancelled _ -> Error "a cancelled order can't ship"

let paid = Paid(DateTimeOffset(2026, 10, 1, 9, 0, 0, TimeSpan.Zero))
printfn "%s" (describe paid)                                   // paid on 2026-10-01
printfn "%A" (ship "1Z999" paid |> Result.map describe)        // Ok "shipped, tracking 1Z999"
printfn "%A" (ship "1Z999" AwaitingPayment)                    // Error "an order must be paid before it ships"

A shipped order always has a tracking number and a payment date, because that's the only way to build a Shipped value. Questions like "what if paidAt is missing?" disappear instead of turning into if statements.

The same idea applies to rules like "a customer needs an email or a phone number, or both". Two option fields allow "neither"; a union doesn't:

▶ Try
type ContactInfo =
    | EmailOnly of email: string
    | PhoneOnly of phone: string
    | EmailAndPhone of email: string * phone: string

Constrained types: single-case unions with private constructors

A string can hold anything. An EmailAddress should only hold a valid email. A single-case union gives the value its own type, and private on the case means only code in the same module can call the constructor. Everyone else goes through a smart constructor that validates and returns a Result:

▶ Try
module Domain =
    type EmailAddress = private EmailAddress of string

    module EmailAddress =
        let create (raw: string) : Result<EmailAddress, string> =
            let text = if isNull raw then "" else raw.Trim().ToLowerInvariant()
            let at = text.IndexOf '@'

            if at > 0 && at = text.LastIndexOf '@' && at < text.Length - 1 then
                Ok(EmailAddress text)
            else
                Error "must be a valid email address"

        let value (EmailAddress text) : string = text

    type Quantity = private Quantity of int

    module Quantity =
        let create (n: int) : Result<Quantity, string> =
            if n >= 1 && n <= 1000 then Ok(Quantity n) else Error "must be between 1 and 1000"

        let value (Quantity n) : int = n

open Domain

printfn "%A" (EmailAddress.create "  Ada@Example.com ")       // Ok EmailAddress "ada@example.com"
printfn "%A" (EmailAddress.create "not an email")             // Error "must be a valid email address"
printfn "%A" (Quantity.create 5 |> Result.map Quantity.value) // Ok 5

// let forged = EmailAddress "nope"
//   error FS1093: The union cases or fields of the type 'EmailAddress' are not accessible from this code location
  • Outside Domain, the only way to get an EmailAddress is EmailAddress.create, so any function that takes an EmailAddress can trust it. That's "parse, don't validate": check once, and keep the proof in the type.
  • private also hides the case from pattern matching outside the module, which is why the module exposes value.
  • Equality and comparison still work (a = b), so these values are fine as Map keys.
  • The type and module share a name; F# compiles the module as EmailAddressModule behind the scenes.
  • A record can be private too: type Money = private { Amount: decimal; Currency: string }.

Why not a class that throws in its constructor, as in C#? You can, and it guarantees validity too. But a constructor can only fail by throwing, and invalid input from users is not exceptional. A smart constructor returns the failure as a value, so the caller can collect every error for one response.

Validation pipelines: fail fast or collect everything

Two shapes come up all the time.

Fail fast when each step needs the previous one: parse the id, then load the order, then check its state. That's Result.bind (or result { let! ... } from the FsToolkit.ErrorHandling library, see the Computation Expressions topic). The first Error stops the chain.

Collect every error when the checks are independent, like the fields of a form. Users want all the red fields at once, not one per round trip. Validate each field on its own, then combine. A small apply helper does the combining:

▶ Try
type FieldError = { Field: string; Message: string }

module Validation =
    /// Applies a validated function to a validated argument, keeping the errors of both.
    let apply (arg: Result<'a, FieldError list>) (fn: Result<'a -> 'b, FieldError list>) : Result<'b, FieldError list> =
        match fn, arg with
        | Ok f, Ok a -> Ok(f a)
        | Error e1, Error e2 -> Error(e1 @ e2)
        | Error e, Ok _
        | Ok _, Error e -> Error e

    let field (name: string) (result: Result<'a, string>) : Result<'a, FieldError list> =
        result |> Result.mapError (fun message -> [ { Field = name; Message = message } ])

type Signup = { Name: string; Age: int; Email: string }

let validateName (raw: string) : Result<string, string> =
    if System.String.IsNullOrWhiteSpace raw then Error "is required" else Ok(raw.Trim())

let validateAge (age: int) : Result<int, string> =
    if age < 18 then Error "must be 18 or older" else Ok age

let validateEmail (raw: string) : Result<string, string> =
    if not (isNull raw) && raw.Contains "@" then Ok raw else Error "must be a valid email address"

let validateSignup (name: string) (age: int) (email: string) : Result<Signup, FieldError list> =
    Ok(fun n a e -> { Name = n; Age = a; Email = e })
    |> Validation.apply (Validation.field "name" (validateName name))
    |> Validation.apply (Validation.field "age" (validateAge age))
    |> Validation.apply (Validation.field "email" (validateEmail email))

printfn "%A" (validateSignup "Ada" 36 "ada@example.com")
// Ok { Name = "Ada"; Age = 36; Email = "ada@example.com" }
printfn "%A" (validateSignup " " 12 "ada@example.com" |> Result.mapError (List.map (fun e -> e.Field)))
// Error ["name"; "age"]

Read validateSignup as "build a Signup from these three validated values". Ok(fun n a e -> ...) is the constructor waiting for its arguments, and each apply feeds it one, or adds to the error list. The FsToolkit.ErrorHandling library packages this as validation { let! n = ... and! a = ... and! e = ... } (F# 5's and!), which is the same thing with nicer syntax.

DTOs: the shape on the wire

Never deserialize JSON straight into domain types. The .NET and C# interop topic shows why: System.Text.Json can't handle unions, missing properties become null in reference fields (like string) that F# thinks can't be null, and a serializer creates values without calling your smart constructors. A record with a public constructor and a "valid" invariant is one crafted JSON body away from holding garbage.

So each endpoint has request and response DTOs: plain records of primitives that mirror the JSON exactly, and two mapping functions:

▶ Try
type PaymentMethod =
    | Card of last4: string
    | Invoice of poNumber: string

type PaymentMethodDto = { Kind: string; Last4: string; PoNumber: string }   // any field may be null

module PaymentMethodDto =
    // Domain -> DTO cannot fail: every domain value has a JSON shape.
    let fromDomain (method: PaymentMethod) : PaymentMethodDto =
        match method with
        | Card last4 -> { Kind = "card"; Last4 = last4; PoNumber = null }
        | Invoice po -> { Kind = "invoice"; Last4 = null; PoNumber = po }

    // DTO -> domain can: the DTO can hold anything.
    let toDomain (dto: PaymentMethodDto) : Result<PaymentMethod, string> =
        match dto.Kind with
        | "card" when not (System.String.IsNullOrWhiteSpace dto.Last4) -> Ok(Card dto.Last4)
        | "card" -> Error "a card payment needs last4"
        | "invoice" when not (System.String.IsNullOrWhiteSpace dto.PoNumber) -> Ok(Invoice dto.PoNumber)
        | "invoice" -> Error "an invoice payment needs a PO number"
        | other -> Error $"unknown payment kind '{other}'"

let dto = PaymentMethodDto.fromDomain (Card "4242")
printfn "%A" (PaymentMethodDto.toDomain dto)                                    // Ok (Card "4242")
printfn "%A" (PaymentMethodDto.toDomain { dto with Kind = "crypto" })           // Error "unknown payment kind 'crypto'"

DTOs also decouple the contract from the model. You can rename a domain case or split a type without breaking clients, and versioning an API means adding a V2 DTO, not changing the domain. The cost is mapping code, which is boring but simple, and the compiler checks it.

Errors across layers

Not every failure is the same kind of thing, and each kind belongs somewhere different:

KindExampleHow it travelsHTTP
Invalid inputemail missing, quantity 0Error(Validation errors)400 Bad Request (with field errors)
Not foundunknown customer idError(CustomerNotFound id)404 Not Found
Business rule says noout of stock, already shippedError(OutOfStock ...)409 Conflict or 422 Unprocessable Content
Not allowedsomeone else's orderError NotOwner403 Forbidden (or 404, to hide that it exists)
Infrastructure failuredatabase timeout, bugan exception500, from middleware

The 4xx codes in the middle are where reasonable teams differ, so pick a convention, write it down and apply it everywhere:

  • 400 vs 422 for invalid input. ASP.NET Core's ValidationProblem and [ApiController] use 400, so most .NET APIs do too. Some teams return 422 for "the JSON was fine, but the values break the rules" and keep 400 for malformed requests. Either works if it's consistent.
  • 409 vs 422 for business rules. 409 Conflict fits "this clashes with the resource's current state" (already shipped, stock taken by someone else, an edit based on a stale version) where retrying later might succeed. 422 fits "this request can never succeed as sent" (over the credit limit). Many teams just use 409 or 422 for every rule failure.

Expected outcomes are Result values. Unexpected failures stay exceptions: wrapping every exception in an Error makes the type lie ("this can fail with a SQL timeout"), hides bugs, and tempts someone to return a 400 for a database outage. Let them reach ASP.NET Core's exception handler, which logs them and returns a 500 with a generic body (never the exception message, which can leak internals).

Each workflow gets its own error union, so its signature documents what can go wrong:

▶ Try
type FieldError = { Field: string; Message: string }

type PlaceOrderError =
    | InvalidRequest of FieldError list
    | CustomerNotFound of customerId: string
    | OutOfStock of sku: string * available: int
    | CreditLimitExceeded

let statusCode (error: PlaceOrderError) : int =
    match error with
    | InvalidRequest _ -> 400
    | CustomerNotFound _ -> 404
    | OutOfStock _ -> 409
    | CreditLimitExceeded -> 422

printfn "%d" (statusCode (OutOfStock("KB-01", 2)))   // 409

The mapping to HTTP lives in one function at the API layer. The workflow never mentions status codes, and when someone adds a case to PlaceOrderError, the compiler warns about this match (FS0025, incomplete matches), which is exactly the reminder you want. Error responses usually follow Problem Details (RFC 9457, application/problem+json): { "type", "title", "status", "detail", "errors" }. ASP.NET Core produces it with Results.Problem and Results.ValidationProblem.

Async workflows return Task<Result<'T, 'E>>. Chaining those by hand means a match after each let!; the FsToolkit.ErrorHandling library's taskResult { } does the plumbing (let! unwraps both the Task and the Result). Writing a few by hand first (the exercises do) shows there's nothing more to it.

Dependencies: functions or DI

The workflow needs a database, a clock and maybe another service. The simplest F# answer: take them as parameters.

▶ Try
open System
open System.Threading.Tasks

type Customer = { Id: string; CreditLimit: decimal }

type PlaceOrderDeps =
    { LoadCustomer: string -> Task<Customer option>
      SaveOrder: string * decimal -> Task<unit>
      Now: unit -> DateTimeOffset }

let placeOrder (deps: PlaceOrderDeps) (customerId: string) (total: decimal) : Task<Result<DateTimeOffset, string>> =
    task {
        match! deps.LoadCustomer customerId with
        | None -> return Error $"customer {customerId} not found"
        | Some customer when total > customer.CreditLimit -> return Error "credit limit exceeded"
        | Some customer ->
            do! deps.SaveOrder(customer.Id, total)
            return Ok(deps.Now())
    }

// In a test: plain functions, no mocking library.
let saved = ResizeArray<string * decimal>()

let fakes =
    { LoadCustomer = fun id -> Task.FromResult(if id = "C1" then Some { Id = "C1"; CreditLimit = 100m } else None)
      SaveOrder = fun order -> task { saved.Add order }
      Now = fun () -> DateTimeOffset(2026, 10, 18, 12, 0, 0, TimeSpan.Zero) }

printfn "%A" (placeOrder fakes "C1" 250m).Result   // Error "credit limit exceeded"
printfn "%A" (placeOrder fakes "C1" 40m).Result    // Ok 10/18/2026 12:00:00 +00:00
printfn "%A" (List.ofSeq saved)                    // [("C1", 40M)]
  • match! awaits and matches in one step.
  • A record of functions keeps signatures short when there are several dependencies. Partial application (let placeOrderForApp = placeOrder realDeps) builds the version the app uses, at the composition root.
  • Taking Now as a function is what makes time-based rules testable; DateTimeOffset.UtcNow inside the workflow isn't. .NET 8 added TimeProvider for the same purpose in C#.

ASP.NET Core's DI container is still there, and you'll use it: it manages lifetimes (a scoped DbContext per request, a singleton HttpClient factory), configuration (IOptions<T>) and logging. The common F# split is: DI at the edges, functions in the core. The endpoint asks DI for services, builds the dependency record, and calls the pure workflow.

One DI trap is worth knowing for interviews: a captive dependency. If a singleton captures a scoped service (say, a function closing over a DbContext), that one DbContext is shared by every request, across threads, for the life of the app. ASP.NET Core's scope validation catches the direct case in Development ("Cannot consume scoped service from singleton"), but a closure built at startup can slip past it. Build per-request dependencies per request.

Minimal APIs in F#

This is what the shell looks like in ASP.NET Core minimal APIs. Handlers are delegates, so F# wraps them in Func (the interop topic explains why):

// Program.fs (not runnable here: needs the ASP.NET Core project SDK)
open System
open System.Threading
open System.Threading.Tasks
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Http
open Microsoft.Extensions.DependencyInjection

let toHttp (result: Result<OrderCreatedDto, PlaceOrderError>) : IResult =
    match result with
    | Ok created -> Results.Created($"/orders/{created.OrderId}", created)
    | Error(InvalidRequest errors) ->
        errors
        |> List.groupBy (fun e -> e.Field)
        |> List.map (fun (field, es) -> field, es |> List.map (fun e -> e.Message) |> Array.ofList)
        |> dict
        |> Results.ValidationProblem                                  // 400 with an "errors" object
    | Error(CustomerNotFound customerId) ->
        Results.Problem(title = $"Customer '{customerId}' was not found.", statusCode = StatusCodes.Status404NotFound)
    | Error(OutOfStock(sku, available)) ->
        Results.Problem(title = "Out of stock", detail = $"Only {available} of {sku} left.", statusCode = StatusCodes.Status409Conflict)
    | Error CreditLimitExceeded ->
        Results.Problem(title = "Credit limit exceeded", statusCode = StatusCodes.Status422UnprocessableEntity)

[<EntryPoint>]
let main args =
    let builder = WebApplication.CreateBuilder(args)
    builder.Services.AddScoped<IOrderStore, SqlOrderStore>() |> ignore   // DI at the edge
    let app = builder.Build()

    app.MapPost(
        "/orders",
        Func<CreateOrderDto, IOrderStore, CancellationToken, Task<IResult>>(fun dto store ct ->
            task {
                let! result = Workflow.placeOrder store ct dto     // the body binds to the DTO, never to domain types
                return toHttp result
            })
    )
    |> ignore

    app.Run()
    0

Minimal APIs bind the handler's parameters by type: a record from the JSON body, a registered service from DI, the request's CancellationToken. The handler is the imperative shell: bind, call the workflow, map the Result.

Giraffe

Many F# teams use Giraffe, a functional layer on top of ASP.NET Core. A handler is a function, and handlers compose with >=> ("then, if that one continued"):

// (not runnable here) needs the Giraffe NuGet package
open Giraffe

let errorToHttp (error: PlaceOrderError) : HttpHandler =
    match error with
    | InvalidRequest errors -> RequestErrors.BAD_REQUEST {| errors = errors |}
    | CustomerNotFound customerId -> RequestErrors.NOT_FOUND {| title = $"Customer '{customerId}' was not found." |}
    | OutOfStock(sku, available) -> RequestErrors.CONFLICT {| title = "Out of stock"; detail = $"Only {available} of {sku} left." |}
    | CreditLimitExceeded -> RequestErrors.UNPROCESSABLE_ENTITY {| title = "Credit limit exceeded" |}

let createOrder: HttpHandler =
    fun next ctx ->
        task {
            let! dto = ctx.BindJsonAsync<CreateOrderDto>()
            let store = ctx.GetService<IOrderStore>()        // DI still works
            let! result = Workflow.placeOrder store ctx.RequestAborted dto   // the request's CancellationToken

            match result with
            | Ok created -> return! (setStatusCode 201 >=> json created) next ctx
            | Error error -> return! errorToHttp error next ctx
        }

let webApp: HttpHandler =
    choose [
        GET >=> route "/health" >=> text "ok"
        GET >=> routef "/orders/%i" getOrder                  // %i parses an int from the path
        POST >=> route "/orders" >=> createOrder
        RequestErrors.NOT_FOUND "Not found"
    ]

// in Program.fs: builder.Services.AddGiraffe(); app.UseGiraffe webApp

Under the hood, HttpHandler is HttpFunc -> HttpContext -> Task<HttpContext option>: it gets the next handler and the context, and either continues (next ctx), finishes the response, or returns None to say "not me", which makes choose try the next route. The last exercise rebuilds this from scratch.

In a real codebase

Side note
  • A project per layer is common: Example.Orders.Domain (types, smart constructors, pure workflows), Example.Orders.Infrastructure (SQL, message queue, object storage), Example.Orders.Api (DTOs, endpoints, DI). F# file order makes the dependency direction visible: domain files come first.
  • Validation errors from smart constructors carry the field name, so the API can return them per field.
  • Workflows that change state often return events (OrderPlaced of ...) rather than the new state. The shell saves them and publishes them to a message broker.
  • C# projects can call the domain through a facade (see the interop topic) or over HTTP.

Common mistakes

  • Primitive obsession: string for emails, ids and SKUs everywhere. Swapping two string arguments compiles.
  • Public union cases on constrained types. Without private, anyone can write EmailAddress "nope".
  • Deserializing request bodies into domain types. It bypasses validation and breaks on unions.
  • Fail-fast validation for forms. Users fix one field per round trip. Collect independent errors.
  • Catching every exception into Error. Expected failures are Results; outages are exceptions and 500s.
  • Status codes inside the workflow. Map errors to HTTP in one place, at the edge.
  • DateTimeOffset.UtcNow or Guid.NewGuid() inside business logic. Pass them in, or tests can't control them.
  • Capturing a scoped service (like a DbContext) in a singleton.

Cheat sheet

// (not runnable here) a summary, not a program
type State = Draft | Paid of DateTimeOffset | Shipped of DateTimeOffset * string   // states, not flags
type Email = private Email of string                     // constrained type
module Email =
    let create raw : Result<Email, string> = ...          // smart constructor
    let value (Email s) = s
Result.bind / result { let! ... }                         // fail fast
Ok ctor |> apply a |> apply b                             // collect errors (validation { and! })
toDomain: Dto -> Result<Domain, FieldError list>         // DTO in
fromDomain: Domain -> Dto                                 // DTO out (total)
type WorkflowError = Invalid of ... | NotFound of ... | Conflict of ...
let statusCode = function Invalid _ -> 400 | NotFound _ -> 404 | Conflict _ -> 409
type Deps = { Load: Id -> Task<X option>; Save: X -> Task<unit>; Now: unit -> DateTimeOffset }
app.MapPost("/x", Func<Dto, IService, CancellationToken, Task<IResult>>(fun dto svc ct -> ...))
GET >=> routef "/orders/%i" getOrder                      // Giraffe

The exercises

  1. Constrained types: EmailAddress and Quantity with private constructors and smart constructors.
  2. Make illegal states unrepresentable: contact details as a union that always has an email or a phone.
  3. DTO to domain and back: map a registration DTO with every field error at once, and build the response DTO.
  4. Errors to HTTP: map workflow errors to status codes and Problem Details, with a safety net for exceptions.
  5. A workflow with injected dependencies: place an order with Task<Result<_, _>>, fakes and no wasted I/O.
  6. Build a Giraffe-style pipeline: handlers, >=>, choose, routing, JSON and a 404 fallback, from scratch.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app