-
Notifications
You must be signed in to change notification settings - Fork 12
Specifying exceptions with Servant and Swagger
Be able to exert fine-grained control over errors defined in our Swagger API specification.
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:
- The generated error responses are sometimes incomplete.
- The generated error responses are sometimes inappropriate.