HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Moduleswagger2-2.8.9Haskell2010

Data.Swagger

Swagger™ is a project used to describe and document RESTful APIs.

The Swagger specification defines a set of files required to describe such an API. These files can then be used by the Swagger-UI project to display the API and Swagger-Codegen to generate clients in various languages. Additional utilities can also take advantage of the resulting files, such as testing tools.

  • 47 types
  • Packageswagger2-2.8.9
  • Exports47
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceSwagger.hs

How to use this library

0 declarations

This section explains how to use this library to work with Swagger specification.

Monoid instances

Virtually all types representing Swagger specification have Monoid instances. The Monoid type class provides two methods — mempty and mappend.

In this library you can use mempty for a default/empty value. For instance:

Example1 expression
encode (mempty :: Swagger)"{\"swagger\":\"2.0\",\"info\":{\"title\":\"\",\"version\":\"\"}}"

As you can see some spec properties (e.g. "version") are there even when the spec is empty. That is because these properties are actually required ones.

You should always override the default (empty) value for these properties, although it is not strictly necessary:

Example1 expression
encode mempty { _infoTitle = "Todo API", _infoVersion = "1.0" }"{\"title\":\"Todo API\",\"version\":\"1.0\"}"

You can merge two values using mappend or its infix version (<>):

Example1 expression
encode $ mempty { _infoTitle = "Todo API" } <> mempty { _infoVersion = "1.0" }"{\"title\":\"Todo API\",\"version\":\"1.0\"}"

This can be useful for combining specifications of endpoints into a whole API specification:

-- /account subAPI specification
accountAPI :: Swagger

-- /task subAPI specification
taskAPI :: Swagger

-- while API specification is just a combination
-- of subAPIs' specifications
api :: Swagger
api = accountAPI <> taskAPI

Lenses and prisms

Note: if you're working with the optics library, take a look at Data.Swagger.Optics.

Since Swagger has a fairly complex structure, lenses and prisms are used to work comfortably with it. In combination with Monoid instances, lenses make it fairly simple to construct/modify any part of the specification:

Example1 expression
:{encode $ (mempty :: Swagger)  & definitions .~ IOHM.fromList [ ("User", mempty & type_ ?~ SwaggerString) ]  & paths .~ IOHM.fromList    [ ("/user", mempty & get ?~ (mempty        & produces ?~ MimeList ["application/json"]        & at 200 ?~ ("OK" & _Inline.schema ?~ Ref (Reference "User"))        & at 404 ?~ "User info not found")) ]:}"{\"swagger\":\"2.0\",\"info\":{\"title\":\"\",\"version\":\"\"},\"paths\":{\"/user\":{\"get\":{\"produces\":[\"application/json\"],\"responses\":{\"200\":{\"description\":\"OK\",\"schema\":{\"$ref\":\"#/definitions/User\"}},\"404\":{\"description\":\"User info not found\"}}}}},\"definitions\":{\"User\":{\"type\":\"string\"}}}"

In the snippet above we declare an API with a single path /user. This path provides method GET which produces application/json output. It should respond with code 200 and body specified by schema User which is defined in definitions property of swagger specification. Alternatively it may respond with code 404 meaning that user info is not found.

For convenience, swagger2 uses classy field lenses. It means that field accessor names can be overloaded for different types. One such common field is description. Many components of a Swagger specification can have descriptions, and you can use the same name for them:

Example2 expressions
encode $ (mempty :: Response) & description .~ "No content""{\"description\":\"No content\"}":{encode $ (mempty :: Schema)  & type_       ?~ SwaggerBoolean  & description ?~ "To be or not to be":}"{\"description\":\"To be or not to be\",\"type\":\"boolean\"}"

ParamSchema is basically the base schema specification and many types contain it (see HasParamSchema). So for convenience, all ParamSchema fields are transitively made fields of the type that has it. For example, you can use type_ to access SwaggerType of Header schema without having to use paramSchema:

Example1 expression
encode $ (mempty :: Header) & type_ ?~ SwaggerNumber"{\"type\":\"number\"}"

Additionally, to simplify working with Response, both Operation and Responses have direct access to it via at code. Example:

Example1 expression
:{encode $ (mempty :: Operation)  & at 404 ?~ "Not found":}"{\"responses\":{\"404\":{\"description\":\"Not found\"}}}"

You might've noticed that type_ has an extra underscore in its name compared to, say, description field accessor. This is because type is a keyword in Haskell. A few other field accessors are modified in this way:

Schema specification

ParamSchema and Schema are the two core types for data model specification.

ParamSchema t specifies all the common properties, available for every data schema. The t parameter imposes some restrictions on type and items properties (see SwaggerType and SwaggerItems).

Schema is used for request and response bodies and allows specifying objects with properties in addition to what ParamSchema provides.

In most cases you will have a Haskell data type for which you would like to define a corresponding schema. To facilitate this use case swagger2 provides two classes for schema encoding. Both these classes provide means to encode types as Swagger schemas.

ToParamSchema is intended to be used for primitive API endpoint parameters, such as query parameters, headers and URL path pieces. Its corresponding value-encoding class is ToHttpApiData (from http-api-data package).

ToSchema is used for request and response bodies and mostly differ from primitive parameters by allowing objects/mappings in addition to primitive types and arrays. Its corresponding value-encoding class is ToJSON (from aeson package).

While lenses and prisms make it easy to define schemas, it might be that you don't need to: ToSchema and ToParamSchema classes both have default Generic-based implementations!

ToSchema default implementation is also aligned with ToJSON default implementation with the only difference being for sum encoding. ToJSON defaults sum encoding to defaultTaggedObject, while ToSchema defaults to something which corresponds to ObjectWithSingleField. This is due to defaultTaggedObject behavior being hard to specify in Swagger.

Here's an example showing ToJSON–ToSchema correspondance:

Example5 expressions
data Person = Person { name :: String, age :: Integer } deriving Genericinstance ToJSON Personinstance ToSchema Personencode (Person "David" 28)"{\"age\":28,\"name\":\"David\"}"encode $ toSchema (Proxy :: Proxy Person)"{\"required\":[\"name\",\"age\"],\"properties\":{\"name\":{\"type\":\"string\"},\"age\":{\"type\":\"integer\"}},\"type\":\"object\"}"

Please note that not all valid Haskell data types will have a proper swagger schema. For example while we can derive a schema for basic enums like

Example3 expressions
data SampleEnum = ChoiceOne | ChoiceTwo deriving Genericinstance ToSchema SampleEnuminstance ToJSON SampleEnum

and for sum types that have constructors with values

Example3 expressions
data SampleSumType = ChoiceInt Int | ChoiceString String deriving Genericinstance ToSchema SampleSumTypeinstance ToJSON SampleSumType

we can not derive a valid schema for a mix of the above. The following will result in a type error

Example2 expressions
data BadMixedType = ChoiceBool Bool | JustTag deriving Genericinstance ToSchema BadMixedType...... • Cannot derive Generic-based Swagger Schema for BadMixedType...   BadMixedType is a mixed sum type (has both unit and non-unit constructors)....   Swagger does not have a good representation for these types....   Use genericDeclareNamedSchemaUnrestricted if you want to derive schema...   that matches aeson's Generic-based toJSON,...   but that's not supported by some Swagger tools....

We can use genericDeclareNamedSchemaUnrestricted to try our best to represent this type as a Swagger Schema and match ToJSON:

Example3 expressions
data BadMixedType = ChoiceBool Bool | JustTag deriving Genericinstance ToSchema BadMixedType where declareNamedSchema = genericDeclareNamedSchemaUnrestricted defaultSchemaOptionsinstance ToJSON BadMixedType

Manipulation

Sometimes you have to work with an imported or generated Swagger. For instance, http://hackage.haskell.org/package/servant-swagger generates basic Swagger for a type-level servant API.

Lenses and prisms can be used to manipulate such specification to add additional information, tags, extra responses, etc. To facilitate common needs, Data.Swagger.Operation module provides useful helpers.

Validation

While ToParamSchema and ToSchema provide means to easily obtain schemas for Haskell types, there is no static mechanism to ensure those instances correspond to the ToHttpApiData or ToJSON instances.

Data.Swagger.Schema.Validation addresses ToJSON/ToSchema validation.

Re-exports

0 declarations

Swagger specification

3 declarations
datadata Swagger
#

This is the root document object for the API specification.

Constructors

  • Swagger
    • _swaggerInfo :: Info

      Provides metadata about the API. The metadata can be used by the clients if needed.

    • _swaggerHost :: Maybe Host

      The host (name or ip) serving the API. It MAY include a port. If the host is not included, the host serving the documentation is to be used (including the port).

    • _swaggerBasePath :: Maybe FilePath

      The base path on which the API is served, which is relative to the host. If it is not included, the API is served directly under the host. The value MUST start with a leading slash (/).

    • _swaggerSchemes :: Maybe [Scheme]

      The transfer protocol of the API. If the schemes is not included, the default scheme to be used is the one used to access the Swagger definition itself.

    • _swaggerConsumes :: MimeList

      A list of MIME types the APIs can consume. This is global to all APIs but can be overridden on specific API calls.

    • _swaggerProduces :: MimeList

      A list of MIME types the APIs can produce. This is global to all APIs but can be overridden on specific API calls.

    • _swaggerPaths :: InsOrdHashMap FilePath PathItem

      The available paths and operations for the API. Holds the relative paths to the individual endpoints. The path is appended to the basePath in order to construct the full URL.

    • _swaggerDefinitions :: Definitions Schema

      An object to hold data types produced and consumed by operations.

    • _swaggerParameters :: Definitions Param

      An object to hold parameters that can be used across operations. This property does not define global parameters for all operations.

    • _swaggerResponses :: Definitions Response

      An object to hold responses that can be used across operations. This property does not define global responses for all operations.

    • _swaggerSecurityDefinitions :: SecurityDefinitions

      Security scheme definitions that can be used across the specification.

    • _swaggerSecurity :: [SecurityRequirement]

      A declaration of which security schemes are applied for the API as a whole. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). Individual operations can override this definition.

    • _swaggerTags :: InsOrdHashSet Tag

      A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared may be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique.

    • _swaggerExternalDocs :: Maybe ExternalDocs

      Additional external documentation.

Instances42Eq, Data, Show, Semigroup, Monoid, FromJSON, …
datadata Host
#

The host (name or ip) serving the API. It MAY include a port.

Constructors

Instances13Eq, Data, Show, IsString, Generic, FromJSON, …
datadata Scheme
#

The transfer protocol of the API.

Instances9Eq, Data, Show, Generic, FromJSON, ToJSON, …

Info types

datadata Info
#

The object provides metadata about the API. The metadata can be used by the clients if needed, and can be presented in the Swagger-UI for convenience.

Constructors

Instances24Eq, Data, Show, Generic, Semigroup, Monoid, …
datadata Contact
#

Contact information for the exposed API.

Constructors

Instances16Eq, Data, Show, Generic, Semigroup, Monoid, …
datadata License
#

License information for the exposed API.

Constructors

Instances13Eq, Data, Show, IsString, Generic, FromJSON, …

PathItem

datadata PathItem
#

Describes the operations available on a single path. A PathItem may be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.

Constructors

Instances33Eq, Data, Show, Semigroup, Monoid, FromJSON, …

Operations

datadata Operation
#

Describes a single API operation on a path.

Constructors

  • Operation
    • _operationTags :: InsOrdHashSet TagName

      A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier.

    • _operationSummary :: Maybe Text

      A short summary of what the operation does. For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters.

    • _operationDescription :: Maybe Text

      A verbose explanation of the operation behavior. GFM syntax can be used for rich text representation.

    • _operationExternalDocs :: Maybe ExternalDocs

      Additional external documentation for this operation.

    • _operationOperationId :: Maybe Text

      Unique string used to identify the operation. The id MUST be unique among all operations described in the API. Tools and libraries MAY use the it to uniquely identify an operation, therefore, it is recommended to follow common programming naming conventions.

    • _operationConsumes :: Maybe MimeList

      A list of MIME types the operation can consume. This overrides the consumes. Just [] MAY be used to clear the global definition.

    • _operationProduces :: Maybe MimeList

      A list of MIME types the operation can produce. This overrides the produces. Just [] MAY be used to clear the global definition.

    • _operationParameters :: [Referenced Param]

      A list of parameters that are applicable for this operation. If a parameter is already defined at the PathItem, the new definition will override it, but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location.

    • _operationResponses :: Responses

      The list of possible responses as they are returned from executing this operation.

    • _operationSchemes :: Maybe [Scheme]

      The transfer protocol for the operation. The value overrides schemes.

    • _operationDeprecated :: Maybe Bool

      Declares this operation to be deprecated. Usage of the declared operation should be refrained. Default value is False.

    • _operationSecurity :: [SecurityRequirement]

      A declaration of which security schemes are applied for this operation. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). This definition overrides any declared top-level security. To remove a top-level security declaration, Just [] can be used.

    • _operationExtensions :: InsOrdHashMap Text Value

      Extensions to the Swagger schema's operations. These automatically get the x- prefix required by the swagger specification.

Instances57Eq, Data, Show, Semigroup, Monoid, FromJSON, …
datadata Tag
#

Allows adding meta data to a single tag that is used by Operation. It is not mandatory to have a Tag per tag used there.

Constructors

Instances17Eq, Data, Ord, Show, IsString, Generic, …

Types and formats

datadata SwaggerType (t :: SwaggerKind Type) where
#
Instances16Eq, Data, Show, FromJSON, ToJSON, AesonDefaultValue, …
datadata CollectionFormat (t :: SwaggerKind Type) where
#
Instances7Eq, Data, Show, FromJSON, ToJSON, …

Parameters

datadata Param
#

Describes a single operation parameter. A unique parameter is defined by a combination of a name and location.

Constructors

  • Param
    • _paramName :: Text

      The name of the parameter. Parameter names are case sensitive.

    • _paramDescription :: Maybe Text

      A brief description of the parameter. This could contain examples of use. GFM syntax can be used for rich text representation.

    • _paramRequired :: Maybe Bool

      Determines whether this parameter is mandatory. If the parameter is in "path", this property is required and its value MUST be true. Otherwise, the property MAY be included and its default value is False.

    • _paramSchema :: ParamAnySchema

      Parameter schema.

Instances28Eq, Data, Show, Semigroup, Monoid, Generic, …
datadata ParamAnySchema
#
Instances12Eq, Data, Show, Generic, FromJSON, ToJSON, …
datadata ParamOtherSchema
#

Constructors

Instances39Eq, Data, Show, Semigroup, Monoid, FromJSON, …
datadata ParamLocation
#

Constructors

  • ParamQuery

    Parameters that are appended to the URL. For example, in /items?id=###, the query parameter is id.

  • ParamHeader

    Custom headers that are expected as part of the request.

  • ParamPath

    Used together with Path Templating, where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in items{itemId}, the path parameter is itemId.

  • ParamFormData

    Used to describe the payload of an HTTP request when either application/x-www-form-urlencoded or multipart/form-data are used as the content type of the request (in Swagger's definition, the consumes property of an operation). This is the only parameter type that can be used to send files, thus supporting the ParamFile type. Since form parameters are sent in the payload, they cannot be declared together with a body parameter for the same operation. Form parameters have a different format based on the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4).

Instances10Eq, Data, Show, Generic, FromJSON, ToJSON, …
datadata Header
#

Constructors

Instances37Eq, Data, Show, Semigroup, Monoid, FromJSON, …
datadata Example
#
Instances10Eq, Data, Show, Generic, Semigroup, Monoid, …

Schemas

datadata ParamSchema (t :: SwaggerKind Type)
#

Constructors

Instances56LabelOptic, HasParamSchema, Eq, Data, Show, Semigroup, …
datadata Schema
#
Instances66Eq, Data, Show, Semigroup, Monoid, Generic, …
datadata NamedSchema
#

A Schema with an optional name. This name can be used in references.

Instances28Eq, Data, Show, Generic, HasSchema, LabelOptic, …
datadata SwaggerItems (t :: SwaggerKind Type) where
#

Items for SwaggerArray schemas.

SwaggerItemsPrimitive should be used only for query params, headers and path pieces. The CollectionFormat t parameter specifies how elements of an array should be displayed. Note that fmt in SwaggerItemsPrimitive fmt schema specifies format for elements of type schema. This is different from the original Swagger's Items Object.

SwaggerItemsObject should be used to specify homogenous array Schemas.

SwaggerItemsArray should be used to specify tuple Schemas.

Instances14LabelOptic, Eq, Data, Show, FromJSON, ToJSON, …
datadata Xml
#

Constructors

  • Xml
    • _xmlName :: Maybe Text

      Replaces the name of the element/attribute used for the described schema property. When defined within the SwaggerItems (items), it will affect the name of the individual XML elements within the list. When defined alongside type being array (outside the items), it will affect the wrapping element and only if wrapped is true. If wrapped is false, it will be ignored.

    • _xmlNamespace :: Maybe Text

      The URL of the namespace definition. Value SHOULD be in the form of a URL.

    • _xmlPrefix :: Maybe Text

      The prefix to be used for the name.

    • _xmlAttribute :: Maybe Bool

      Declares whether the property definition translates to an attribute instead of an element. Default value is False.

    • _xmlWrapped :: Maybe Bool

      MAY be used only for an array definition. Signifies whether the array is wrapped (for example, <books><book><book></books>) or unwrapped (<book><book>). Default value is False. The definition takes effect only when defined alongside type being array (outside the items).

Instances18Eq, Data, Show, Generic, FromJSON, ToJSON, …
datadata AdditionalProperties
#
Instances6Eq, Data, Show, FromJSON, ToJSON, HasAdditionalProperties

Responses

datadata Responses
#

A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. It is not expected from the documentation to necessarily cover all possible HTTP response codes, since they may not be known in advance. However, it is expected from the documentation to cover a successful operation response and any known errors.

Constructors

Instances30Eq, Data, Show, Semigroup, Monoid, FromJSON, …
datadata Response
#

Describes a single response from an API Operation.

Constructors

Instances29Eq, Data, Show, IsString, Semigroup, Monoid, …

Security

datadata SecurityScheme
#

Constructors

Instances17Eq, Data, Show, Semigroup, FromJSON, ToJSON, …
datadata SecuritySchemeType
#
Instances12Eq, Data, Show, Generic, FromJSON, ToJSON, …
newtypenewtype SecurityRequirement
#

Lists the required security schemes to execute this operation. The object can have multiple security schemes declared in it which are all required (that is, there is a logical AND between the schemes).

Instances10Eq, Data, Read, Show, Semigroup, Monoid, …
newtypenewtype SecurityDefinitions
#
Instances16Eq, Data, Show, Generic, Semigroup, Monoid, …

API key

datadata ApiKeyParams
#

Constructors

Instances7Eq, Data, Show, Generic, FromJSON, ToJSON, …
datadata ApiKeyLocation
#

The location of the API key.

Instances7Eq, Data, Show, Generic, FromJSON, ToJSON, …

OAuth2

datadata OAuth2Params
#

Constructors

Instances12Eq, Data, Show, FromJSON, ToJSON, Generic, …
datadata OAuth2Flow
#
Instances8Eq, Data, Show, Generic, FromJSON, ToJSON, …
typetype AuthorizationURL = Text
#

The authorization URL to be used for OAuth2 flow. This SHOULD be in the form of a URL.

typetype TokenURL = Text
#

The token URL to be used for OAuth2 flow. This SHOULD be in the form of a URL.

External documentation

datadata ExternalDocs
#

Allows referencing an external resource for extended documentation.

Constructors

Instances20Eq, Data, Ord, Show, Generic, Semigroup, …

References

newtypenewtype Reference
#

A simple object to allow referencing other definitions in the specification. It can be used to reference parameters and responses that are defined at the top level for reuse.

Instances5Eq, Data, Show, FromJSON, ToJSON
datadata Referenced a
#

Constructors

Instances21Functor, LabelOptic, HasAllOf, HasDefault, HasParameters, HasSchema, …

Miscellaneous

newtypenewtype MimeList
#
Instances13Eq, Data, Show, Semigroup, Monoid, FromJSON, …
newtypenewtype URL
#

Constructors

Instances11Eq, Data, Ord, Show, Hashable, FromJSON, …
  • Eq URLDefined in swagger2-2.8.9 · Data.Swagger.Internal
  • Data URLDefined in swagger2-2.8.9 · Data.Swagger.Internal
  • Ord URLDefined in swagger2-2.8.9 · Data.Swagger.Internal
  • Show URLDefined in swagger2-2.8.9 · Data.Swagger.Internal
  • Hashable URLDefined in swagger2-2.8.9 · Data.Swagger.Internal
  • FromJSON URLDefined in swagger2-2.8.9 · Data.Swagger.Internal
  • ToJSON URLDefined in swagger2-2.8.9 · Data.Swagger.Internal
  • SwaggerMonoid URLDefined in swagger2-2.8.9 · Data.Swagger.Internal
  • HasUrl ExternalDocs URLDefined in swagger2-2.8.9 · Data.Swagger.Lens
  • HasUrl Contact (Maybe URL)Defined in swagger2-2.8.9 · Data.Swagger.Lens
  • HasUrl License (Maybe URL)Defined in swagger2-2.8.9 · Data.Swagger.Lens