Skip to content
This repository was archived by the owner on Mar 1, 2019. It is now read-only.

Specifying exceptions with Servant and Swagger

Jonathan Knowles edited this page Feb 21, 2019 · 27 revisions

Motivation

Be able to exert fine-grained control over errors defined in our Swagger API specification.

Background

Our API is defined in Haskell with Servant, and translated into Swagger format using the servant-swagger library.

Swagger makes it possible to specify that an endpoint can return one or more errors. For example:

"responses" :
  { "200" : { "schema" : {"$ref" : "#/definitions/Location" }
            , "description" : "the matching location" } }
  , "404" : { "description" : "a matching location was not found" }

By default, Servant doesn't provide an easy way for API authors to specify errors that might be returned by individual endpoints.

In light of this, servant-swagger takes the approach of auto-generating suitable 400 (invalid input) and/or 404 (not found) errors when various Servant combinators appear in the API. For example, when a Capture combinator is used, servant-swagger automatically inserts a 404 (not found) error in the generated Swagger output:

Haskell definition:

type AddLocation = "location" 
  :> "add"
  :> Summary "Add a new location" 
  :> Capture "locationName" Text
  :> Put '[JSON] Location

Swagger output:

"/location/add/{locationName}" :
  { "put" :
    { "parameters" : [ { "in" : "path"
                       , "type" : "string"
                       , "name" : "locationName"
                       , "required" : true } ]
    , "responses" :
      { "200" : { "schema" : { "$ref" : "#/definitions/Location" }
                , "description" : "the added location" }
      , "404" : { "description" : "`locationName` not found" } }
    , "summary" : "Add a new location"
    , "produces" : ["application/json;charset=utf-8"] } }

However, auto-generation of error responses has two problems:

  1. The generated error responses are sometimes incomplete.
  2. The generated error responses are sometimes inappropriate.
Clone this wiki locally