Maintainer | Nickolay Kudasov <nickolay@getshoptv.com> |
---|---|
Stability | experimental |
Safe Haskell | None |
Language | Haskell2010 |
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.
Synopsis
- module Data.Swagger.Lens
- module Data.Swagger.Operation
- module Data.Swagger.ParamSchema
- module Data.Swagger.Schema
- module Data.Swagger.Schema.Validation
- data Swagger = Swagger {
- _swaggerInfo :: Info
- _swaggerHost :: Maybe Host
- _swaggerBasePath :: Maybe FilePath
- _swaggerSchemes :: Maybe [Scheme]
- _swaggerConsumes :: MimeList
- _swaggerProduces :: MimeList
- _swaggerPaths :: InsOrdHashMap FilePath PathItem
- _swaggerDefinitions :: Definitions Schema
- _swaggerParameters :: Definitions Param
- _swaggerResponses :: Definitions Response
- _swaggerSecurityDefinitions :: Definitions SecurityScheme
- _swaggerSecurity :: [SecurityRequirement]
- _swaggerTags :: InsOrdHashSet Tag
- _swaggerExternalDocs :: Maybe ExternalDocs
- data Host = Host {}
- data Scheme
- data Info = Info {}
- data Contact = Contact {}
- data License = License {
- _licenseName :: Text
- _licenseUrl :: Maybe URL
- data PathItem = PathItem {}
- data Operation = Operation {
- _operationTags :: InsOrdHashSet TagName
- _operationSummary :: Maybe Text
- _operationDescription :: Maybe Text
- _operationExternalDocs :: Maybe ExternalDocs
- _operationOperationId :: Maybe Text
- _operationConsumes :: Maybe MimeList
- _operationProduces :: Maybe MimeList
- _operationParameters :: [Referenced Param]
- _operationResponses :: Responses
- _operationSchemes :: Maybe [Scheme]
- _operationDeprecated :: Maybe Bool
- _operationSecurity :: [SecurityRequirement]
- data Tag = Tag {}
- type TagName = Text
- data SwaggerType t where
- type Format = Text
- type Definitions = InsOrdHashMap Text
- data CollectionFormat t where
- data Param = Param {}
- data ParamAnySchema
- data ParamOtherSchema = ParamOtherSchema {}
- data ParamLocation
- type ParamName = Text
- data Header = Header {}
- type HeaderName = Text
- data Example = Example {}
- data ParamSchema (t :: SwaggerKind *) = ParamSchema {
- _paramSchemaDefault :: Maybe Value
- _paramSchemaType :: Maybe (SwaggerType t)
- _paramSchemaFormat :: Maybe Format
- _paramSchemaItems :: Maybe (SwaggerItems t)
- _paramSchemaMaximum :: Maybe Scientific
- _paramSchemaExclusiveMaximum :: Maybe Bool
- _paramSchemaMinimum :: Maybe Scientific
- _paramSchemaExclusiveMinimum :: Maybe Bool
- _paramSchemaMaxLength :: Maybe Integer
- _paramSchemaMinLength :: Maybe Integer
- _paramSchemaPattern :: Maybe Pattern
- _paramSchemaMaxItems :: Maybe Integer
- _paramSchemaMinItems :: Maybe Integer
- _paramSchemaUniqueItems :: Maybe Bool
- _paramSchemaEnum :: Maybe [Value]
- _paramSchemaMultipleOf :: Maybe Scientific
- data Schema = Schema {
- _schemaTitle :: Maybe Text
- _schemaDescription :: Maybe Text
- _schemaRequired :: [ParamName]
- _schemaAllOf :: Maybe [Referenced Schema]
- _schemaProperties :: InsOrdHashMap Text (Referenced Schema)
- _schemaAdditionalProperties :: Maybe AdditionalProperties
- _schemaDiscriminator :: Maybe Text
- _schemaReadOnly :: Maybe Bool
- _schemaXml :: Maybe Xml
- _schemaExternalDocs :: Maybe ExternalDocs
- _schemaExample :: Maybe Value
- _schemaMaxProperties :: Maybe Integer
- _schemaMinProperties :: Maybe Integer
- _schemaParamSchema :: ParamSchema SwaggerKindSchema
- data NamedSchema = NamedSchema {}
- data SwaggerItems t where
- data Xml = Xml {
- _xmlName :: Maybe Text
- _xmlNamespace :: Maybe Text
- _xmlPrefix :: Maybe Text
- _xmlAttribute :: Maybe Bool
- _xmlWrapped :: Maybe Bool
- type Pattern = Text
- data AdditionalProperties
- data Responses = Responses {}
- data Response = Response {}
- type HttpStatusCode = Int
- data SecurityScheme = SecurityScheme {}
- data SecuritySchemeType
- newtype SecurityRequirement = SecurityRequirement {}
- data ApiKeyParams = ApiKeyParams {}
- data ApiKeyLocation
- data OAuth2Params = OAuth2Params {}
- data OAuth2Flow
- type AuthorizationURL = Text
- type TokenURL = Text
- data ExternalDocs = ExternalDocs {}
- newtype Reference = Reference {
- getReference :: Text
- data Referenced a
- newtype MimeList = MimeList {
- getMimeList :: [MediaType]
- newtype URL = URL {}
How to use this library
This section explains how to use this library to work with Swagger specification.
Monoid
instances
Monoid
Virtually all types representing Swagger specification have
instances.
The Monoid
type class provides two methods — Monoid
and mempty
.mappend
In this library you can use
for a default/empty value. For instance:mempty
>>>
encode (mempty :: Swagger)
"{\"swagger\":\"2.0\",\"info\":{\"version\":\"\",\"title\":\"\"}}"
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:
>>>
encode mempty { _infoTitle = "Todo API", _infoVersion = "1.0" }
"{\"version\":\"1.0\",\"title\":\"Todo API\"}"
You can merge two values using
or its infix version mappend
(
:<>
)
>>>
encode $ mempty { _infoTitle = "Todo API" } <> mempty { _infoVersion = "1.0" }
"{\"version\":\"1.0\",\"title\":\"Todo API\"}"
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
Since
has a fairly complex structure, lenses and prisms are used
to work comfortably with it. In combination with Swagger
instances, lenses
make it fairly simple to construct/modify any part of the specification:Monoid
>>>
:{
encode $ (mempty :: Swagger) & definitions .~ [ ("User", mempty & type_ ?~ SwaggerString) ] & paths .~ [ ("/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\":{\"version\":\"\",\"title\":\"\"},\"paths\":{\"/user\":{\"get\":{\"produces\":[\"application/json\"],\"responses\":{\"404\":{\"description\":\"User info not found\"},\"200\":{\"schema\":{\"$ref\":\"#/definitions/User\"},\"description\":\"OK\"}}}}},\"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
property of swagger specification.
Alternatively it may respond with code definitions
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
. Many components of a Swagger specification
can have descriptions, and you can use the same name for them:description
>>>
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\"}"
is basically the base schema specification and many types contain it (see ParamSchema
).
So for convenience, all HasParamSchema
fields are transitively made fields of the type that has it.
For example, you can use ParamSchema
to access type_
of SwaggerType
schema without having to use Header
:paramSchema
>>>
encode $ (mempty :: Header) & type_ ?~ SwaggerNumber
"{\"type\":\"number\"}"
Additionally, to simplify working with
, both Response
and Operation
have direct access to it via Responses
. Example:at
code
>>>
:{
encode $ (mempty :: Operation) & at 404 ?~ "Not found" :} "{\"responses\":{\"404\":{\"description\":\"Not found\"}}}"
You might've noticed that
has an extra underscore in its name
compared to, say, type_
field accessor.
This is because description
type
is a keyword in Haskell.
A few other field accessors are modified in this way:
Schema specification
and ParamSchema
are the two core types for data model specification.Schema
specifies all the common properties, available for every data schema.
The ParamSchema
tt
parameter imposes some restrictions on type
and items
properties (see
and SwaggerType
).SwaggerItems
is used for request and response bodies and allows specifying objects
with properties in addition to what Schema
provides.ParamSchema
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.
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 ToParamSchema
(from ToHttpApiData
http-api-data
package).
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 ToSchema
(from ToJSON
aeson
package).
While lenses and prisms make it easy to define schemas, it might be that you don't need to:
and ToSchema
classes both have default ToParamSchema
-based implementations!Generic
default implementation is also aligned with ToSchema
default implementation with
the only difference being for sum encoding. ToJSON
defaults sum encoding to ToJSON
,
while defaultTaggedObject
defaults to something which corresponds to ToSchema
. This is due to
ObjectWithSingleField
behavior being hard to specify in Swagger.defaultTaggedObject
Here's an example showing
–ToJSON
correspondance:ToSchema
>>>
data Person = Person { name :: String, age :: Integer } deriving Generic
>>>
instance ToJSON Person
>>>
instance ToSchema Person
>>>
encode (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
>>>
data SampleEnum = ChoiceOne | ChoiceTwo deriving Generic
>>>
instance ToSchema SampleEnum
>>>
instance ToJSON SampleEnum
and for sum types that have constructors with values
>>>
data SampleSumType = ChoiceInt Int | ChoiceString String deriving Generic
>>>
instance ToSchema SampleSumType
>>>
instance ToJSON SampleSumType
we can not derive a valid schema for a mix of the above. The following will result in a type error
Manipulation
Sometimes you have to work with an imported or generated
.
For instance, http://hackage.haskell.org/package/servant-swagger generates basic Swagger
for a type-level servant API.Swagger
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
and ToParamSchema
provide means to easily obtain schemas for Haskell types,
there is no static mechanism to ensure those instances correspond to the ToSchema
or ToHttpApiData
instances.ToJSON
Data.Swagger.Schema.Validation
addresses
/ToJSON
validation.ToSchema
Re-exports
module Data.Swagger.Lens
module Data.Swagger.Operation
module Data.Swagger.ParamSchema
module Data.Swagger.Schema
Swagger specification
This is the root document object for the API specification.
Swagger | |
|
Instances
The host (name or ip) serving the API. It MAY include a port.
Instances
Eq Host Source # | |
Data Host Source # | |
Defined in Data.Swagger.Internal gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Host -> c Host # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Host # dataTypeOf :: Host -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c Host) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Host) # gmapT :: (forall b. Data b => b -> b) -> Host -> Host # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Host -> r # gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Host -> r # gmapQ :: (forall d. Data d => d -> u) -> Host -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Host -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Host -> m Host # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Host -> m Host # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Host -> m Host # | |
Show Host Source # | |
IsString Host Source # | |
Defined in Data.Swagger.Internal fromString :: String -> Host # | |
Generic Host Source # | |
ToJSON Host Source # | |
Defined in Data.Swagger.Internal | |
FromJSON Host Source # | |
HasName Host HostName Source # | |
HasHost Swagger (Maybe Host) Source # | |
HasPort Host (Maybe PortNumber) Source # | |
Defined in Data.Swagger.Lens | |
type Rep Host Source # | |
Defined in Data.Swagger.Internal type Rep Host = D1 (MetaData "Host" "Data.Swagger.Internal" "swagger2-2.4-7GGQol8nqP59uwH1hSShKy" False) (C1 (MetaCons "Host" PrefixI True) (S1 (MetaSel (Just "_hostName") NoSourceUnpackedness NoSourceStrictness DecidedLazy) (Rec0 HostName) :*: S1 (MetaSel (Just "_hostPort") NoSourceUnpackedness NoSourceStrictness DecidedLazy) (Rec0 (Maybe PortNumber)))) |
The transfer protocol of the API.
Instances
Eq Scheme Source # | |
Data Scheme Source # | |
Defined in Data.Swagger.Internal gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Scheme -> c Scheme # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Scheme # toConstr :: Scheme -> Constr # dataTypeOf :: Scheme -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c Scheme) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Scheme) # gmapT :: (forall b. Data b => b -> b) -> Scheme -> Scheme # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Scheme -> r # gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Scheme -> r # gmapQ :: (forall d. Data d => d -> u) -> Scheme -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Scheme -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Scheme -> m Scheme # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Scheme -> m Scheme # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Scheme -> m Scheme # | |
Show Scheme Source # | |
Generic Scheme Source # | |
ToJSON Scheme Source # | |
Defined in Data.Swagger.Internal | |
FromJSON Scheme Source # | |
HasSchemes Operation (Maybe [Scheme]) Source # | |
HasSchemes Swagger (Maybe [Scheme]) Source # | |
type Rep Scheme Source # | |
Defined in Data.Swagger.Internal type Rep Scheme = D1 (MetaData "Scheme" "Data.Swagger.Internal" "swagger2-2.4-7GGQol8nqP59uwH1hSShKy" False) ((C1 (MetaCons "Http" PrefixI False) (U1 :: Type -> Type) :+: C1 (MetaCons "Https" PrefixI False) (U1 :: Type -> Type)) :+: (C1 (MetaCons "Ws" PrefixI False) (U1 :: Type -> Type) :+: C1 (MetaCons "Wss" PrefixI False) (U1 :: Type -> Type))) |
Info types
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.
Info | |
|
Instances
Contact information for the exposed API.
Contact | |
|
Instances
License information for the exposed API.
License | |
|
Instances
Eq License Source # | |
Data License Source # | |
Defined in Data.Swagger.Internal gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> License -> c License # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c License # toConstr :: License -> Constr # dataTypeOf :: License -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c License) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c License) # gmapT :: (forall b. Data b => b -> b) -> License -> License # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> License -> r # gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> License -> r # gmapQ :: (forall d. Data d => d -> u) -> License -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> License -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> License -> m License # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> License -> m License # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> License -> m License # | |
Show License Source # | |
IsString License Source # | |
Defined in Data.Swagger.Internal fromString :: String -> License # | |
Generic License Source # | |
ToJSON License Source # | |
Defined in Data.Swagger.Internal | |
FromJSON License Source # | |
HasName License Text Source # | |
HasLicense Info (Maybe License) Source # | |
HasUrl License (Maybe URL) Source # | |
type Rep License Source # | |
Defined in Data.Swagger.Internal type Rep License = D1 (MetaData "License" "Data.Swagger.Internal" "swagger2-2.4-7GGQol8nqP59uwH1hSShKy" False) (C1 (MetaCons "License" PrefixI True) (S1 (MetaSel (Just "_licenseName") NoSourceUnpackedness NoSourceStrictness DecidedLazy) (Rec0 Text) :*: S1 (MetaSel (Just "_licenseUrl") NoSourceUnpackedness NoSourceStrictness DecidedLazy) (Rec0 (Maybe URL)))) |
PathItem
Describes the operations available on a single path.
A
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.PathItem
PathItem | |
|
Instances
Operations
Describes a single API operation on a path.
Operation | |
|
Instances
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.
Tag | |
|
Instances
Types and formats
data SwaggerType t where Source #
Instances
type Definitions = InsOrdHashMap Text Source #
A list of definitions that can be used in references.
data CollectionFormat t where Source #
Determines the format of the array.
Instances
Parameters
Describes a single operation parameter. A unique parameter is defined by a combination of a name and location.
Param | |
|
Instances
data ParamAnySchema Source #
Instances
data ParamOtherSchema Source #
ParamOtherSchema | |
|
Instances
data ParamLocation Source #
ParamQuery | Parameters that are appended to the URL.
For example, in |
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 |
ParamFormData | Used to describe the payload of an HTTP request when either |
Instances
Header | |
|
Instances
type HeaderName = Text Source #
Instances
Eq Example Source # | |
Data Example Source # | |
Defined in Data.Swagger.Internal gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Example -> c Example # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Example # toConstr :: Example -> Constr # dataTypeOf :: Example -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c Example) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Example) # gmapT :: (forall b. Data b => b -> b) -> Example -> Example # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Example -> r # gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Example -> r # gmapQ :: (forall d. Data d => d -> u) -> Example -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Example -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Example -> m Example # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Example -> m Example # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Example -> m Example # | |
Show Example Source # | |
Generic Example Source # | |
Semigroup Example Source # | |
Monoid Example Source # | |
ToJSON Example Source # | |
Defined in Data.Swagger.Internal | |
FromJSON Example Source # | |
HasExamples Response (Maybe Example) Source # | |
type Rep Example Source # | |
Defined in Data.Swagger.Internal |
Schemas
data ParamSchema (t :: SwaggerKind *) Source #
ParamSchema | |
|
Instances
Instances
data NamedSchema Source #
A
with an optional name.
This name can be used in references.Schema
Instances
data SwaggerItems t where Source #
Items for
schemas.SwaggerArray
should be used only for query params, headers and path pieces.
The SwaggerItemsPrimitive
parameter specifies how elements of an array should be displayed.
Note that CollectionFormat
tfmt
in
specifies format for elements of type SwaggerItemsPrimitive
fmt schemaschema
.
This is different from the original Swagger's Items Object.
should be used to specify homogenous array SwaggerItemsObject
s.Schema
should be used to specify tuple SwaggerItemsArray
s.Schema