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.
- module Data.Swagger.Lens
- module Data.Swagger.ParamSchema
- module Data.Swagger.Schema
- data Swagger = Swagger {
- _info :: Info
- _host :: Maybe Host
- _basePath :: Maybe FilePath
- _schemes :: Maybe [Scheme]
- _consumes :: MimeList
- _produces :: MimeList
- _paths :: Paths
- _definitions :: HashMap Text Schema
- _parameters :: HashMap Text Param
- _responses :: HashMap Text Response
- _securityDefinitions :: HashMap Text SecurityScheme
- _security :: [SecurityRequirement]
- _tags :: [Tag]
- _externalDocs :: Maybe ExternalDocs
- data Host = Host {}
- data Scheme
- data Info = Info {}
- data Contact = Contact {}
- data License = License {
- _licenseName :: Text
- _licenseUrl :: Maybe URL
- data Paths = Paths {}
- data PathItem = PathItem {}
- data Operation = Operation {
- _operationTags :: [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
- 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 = ParamSchema {
- _paramSchemaDefault :: Maybe Value
- _paramSchemaType :: 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 Text
- _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 [Schema]
- _schemaProperties :: HashMap Text (Referenced Schema)
- _schemaAdditionalProperties :: Maybe Schema
- _schemaDiscriminator :: Maybe Text
- _schemaReadOnly :: Maybe Bool
- _schemaXml :: Maybe Xml
- _schemaExternalDocs :: Maybe ExternalDocs
- _schemaExample :: Maybe Value
- _schemaMaxProperties :: Maybe Integer
- _schemaMinProperties :: Maybe Integer
- _schemaParamSchema :: ParamSchema Schema
- data SwaggerItems t where
- SwaggerItemsPrimitive :: Maybe (CollectionFormat t) -> ParamSchema t -> SwaggerItems t
- SwaggerItemsObject :: Referenced Schema -> SwaggerItems Schema
- SwaggerItemsArray :: [Referenced Schema] -> SwaggerItems Schema
- data Xml = Xml {
- _xmlName :: Maybe Text
- _xmlNamespace :: Maybe Text
- _xmlPrefix :: Maybe Text
- _xmlAttribute :: Maybe Bool
- _xmlWrapped :: Maybe Bool
- 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 modify this structure. In combination with Swagger
instances, lenses
also make it fairly simple to construct/modify any part of the specification:Monoid
>>>
:{
encode $ mempty & pathsMap .~ [ ("/user", mempty & pathItemGet ?~ (mempty & operationProduces ?~ MimeList ["application/json"] & operationResponses .~ (mempty & responsesResponses . at 200 ?~ Inline (mempty & responseSchema ?~ Ref (Reference "#/definitions/User")))))] :} "{\"/user\":{\"get\":{\"responses\":{\"200\":{\"schema\":{\"$ref\":\"#/definitions/#/definitions/User\"},\"description\":\"\"}},\"produces\":[\"application/json\"]}}}"
In the snippet above we declare API paths with a single path /user
providing method GET
which produces application/json
output and should respond with code 200
and body specified
by schema User
(which should be defined in definitions
property of swagger specification).
Since
is basically the base schema specification, a special
ParamSchema
class has been introduced to generalize HasParamSchema
lenses
and allow them to be used by any type that has a ParamSchema
:ParamSchema
>>>
:{
encode $ mempty & schemaTitle ?~ "Email" & schemaType .~ SwaggerString & schemaFormat ?~ "email" :} "{\"format\":\"email\",\"title\":\"Email\",\"type\":\"string\"}"
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 thise use case this library 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\"],\"type\":\"object\",\"properties\":{\"age\":{\"type\":\"integer\"},\"name\":{\"type\":\"string\"}}}"
Re-exports
module Data.Swagger.Lens
module Data.Swagger.ParamSchema
module Data.Swagger.Schema
Swagger specification
This is the root document object for the API specification.
Swagger | |
|
The host (name or ip) serving the API. It MAY include a port.
The transfer protocol of the API.
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 | |
|
Contact information for the exposed API.
Contact | |
|
License information for the exposed API.
License | |
|
Paths
The available paths and operations for the API.
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 | |
|
Operations
Describes a single API operation on a path.
Operation | |
|
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 | |
|
Types and formats
data SwaggerType t where Source
Eq (SwaggerType t) Source | |
Typeable * t => Data (SwaggerType t) Source | |
Data (SwaggerType Schema) Source | |
Data (SwaggerType ParamOtherSchema) Source | |
Show (SwaggerType t) Source | |
ToJSON (SwaggerType t) Source | |
FromJSON (SwaggerType t) Source | |
FromJSON (SwaggerType Schema) Source | |
FromJSON (SwaggerType ParamOtherSchema) Source | |
SwaggerMonoid (SwaggerType t) Source |
data CollectionFormat t where Source
Determines the format of the array.
Parameters
Describes a single operation parameter. A unique parameter is defined by a combination of a name and location.
Param | |
|
data ParamAnySchema Source
data ParamOtherSchema Source
ParamOtherSchema | |
|
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 |
Header | |
|
type HeaderName = Text Source
Schemas
data ParamSchema t Source
ParamSchema | |
|
Eq (ParamSchema t) Source | |
(Data t, Data (SwaggerType t), Data (SwaggerItems t)) => Data (ParamSchema t) Source | |
Show (ParamSchema t) Source | |
Generic (ParamSchema t) Source | |
ToJSON (ParamSchema t) Source | |
(FromJSON (SwaggerType t), FromJSON (SwaggerItems t)) => FromJSON (ParamSchema t) Source | |
Monoid (ParamSchema t) Source | |
SwaggerMonoid (ParamSchema t) Source | |
HasParamSchema (ParamSchema t) t Source | |
type Rep (ParamSchema t) Source |
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
SwaggerItemsPrimitive :: Maybe (CollectionFormat t) -> ParamSchema t -> SwaggerItems t | |
SwaggerItemsObject :: Referenced Schema -> SwaggerItems Schema | |
SwaggerItemsArray :: [Referenced Schema] -> SwaggerItems Schema |
Eq (SwaggerItems t) Source | |
Data t => Data (SwaggerItems t) Source | |
Data (SwaggerItems Schema) Source | |
Show (SwaggerItems t) Source | |
ToJSON (SwaggerItems t) Source | |
(FromJSON (CollectionFormat t), FromJSON (ParamSchema t)) => FromJSON (SwaggerItems t) Source | |
FromJSON (SwaggerItems Schema) Source |
Xml | |
|
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.
Responses | |
|
Describes a single response from an API Operation.
Response | |
|
type HttpStatusCode = Int Source
Security
data SecurityScheme Source
SecurityScheme | |
|
data SecuritySchemeType Source
newtype SecurityRequirement Source
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).
API key
data ApiKeyParams Source
ApiKeyParams | |
|
data ApiKeyLocation Source
The location of the API key.
OAuth2
data OAuth2Params Source
OAuth2Params | |
|
data OAuth2Flow Source
type AuthorizationURL = Text Source
The authorization URL to be used for OAuth2 flow. This SHOULD be in the form of a URL.
The token URL to be used for OAuth2 flow. This SHOULD be in the form of a URL.
External documentation
data ExternalDocs Source
Allows referencing an external resource for extended documentation.
ExternalDocs | |
|
References
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.
data Referenced a Source
Eq a => Eq (Referenced a) Source | |
Data a => Data (Referenced a) Source | |
Show a => Show (Referenced a) Source | |
ToJSON (Referenced Response) Source | |
ToJSON (Referenced Schema) Source | |
ToJSON (Referenced Param) Source | |
FromJSON (Referenced Response) Source | |
FromJSON (Referenced Schema) Source | |
FromJSON (Referenced Param) Source | |
Monoid a => SwaggerMonoid (Referenced a) Source |
Miscellaneous
MimeList | |
|