1{-# OPTIONS_GHC -fconstraint-solver-iterations=5 #-}
3{-# LANGUAGE DataKinds #-}
4{-# LANGUAGE DeriveDataTypeable #-}
5{-# LANGUAGE DeriveGeneric #-}
6{-# LANGUAGE DeriveTraversable #-}
7{-# LANGUAGE FlexibleContexts #-}
8{-# LANGUAGE FlexibleInstances #-}
10{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11{-# LANGUAGE OverloadedStrings #-}
12{-# LANGUAGE RecordWildCards #-}
13{-# LANGUAGE ScopedTypeVariables #-}
14{-# LANGUAGE StandaloneDeriving #-}
15{-# LANGUAGE TemplateHaskell #-}
16{-# LANGUAGE TypeFamilies #-}
17{-# LANGUAGE UndecidableInstances #-}
18module Data.OpenApi.Internal where
23import Control.Applicative
24import Control.Lens ((&), (.~), (?~))
25import Data.Aeson hiding (Encoding)
26import qualified Data.Aeson.Types as JSON
27import Data.Data (Constr, Data (..), DataType, Fixity (..), Typeable,
28 constrIndex, mkConstr, mkDataType)
29import Data.Hashable (Hashable (..))
30import qualified Data.HashMap.Strict as HashMap
31import Data.HashSet.InsOrd (InsOrdHashSet)
33import qualified Data.Map as Map
34import Data.Monoid (Monoid (..))
35import Data.Scientific (Scientific)
36import Data.Semigroup.Compat (Semigroup (..))
37import Data.String (IsString (..))
38import Data.Text (Text)
39import qualified Data.Text as Text
40import Data.Text.Encoding (encodeUtf8)
41import GHC.Generics (Generic)
42import Network.HTTP.Media (MediaType, mainType, parameters, parseAccept, subType, (//),
44import Text.Read (readMaybe)
45import Test.QuickCheck.Arbitrary.Generic
47import Data.HashMap.Strict.InsOrd (InsOrdHashMap)
48import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
50import Generics.SOP.TH (deriveGeneric)
51import Data.OpenApi.Internal.AesonUtils (sopSwaggerGenericToJSON
52 ,sopSwaggerGenericToJSONWithOpts
53 ,sopSwaggerGenericParseJSON
54 ,HasSwaggerAesonOptions(..)
55 ,AesonDefaultValue(..)
56 ,mkSwaggerAesonOptions
59import Data.OpenApi.Internal.Utils
60import Data.OpenApi.Internal.AesonUtils (sopSwaggerGenericToEncoding)
63-- >>> :seti -XDataKinds
64-- >>> import Data.Aeson
66-- | A list of definitions that can be used in references.
67type Definitions = InsOrdHashMap Text
69-- | This is the root document object for the API specification.
71 { -- | Provides metadata about the API.
72 -- The metadata can be used by the clients if needed.
75 -- | An array of Server Objects, which provide connectivity information
76 -- to a target server. If the servers property is not provided, or is an empty array,
77 -- the default value would be a 'Server' object with a url value of @/@.
78 , _openApiServers :: [Server]
80 -- | The available paths and operations for the API.
81 , _openApiPaths :: InsOrdHashMap FilePath PathItem
83 -- | An element to hold various schemas for the specification.
84 , _openApiComponents :: Components
86 -- | A declaration of which security mechanisms can be used across the API.
87 -- The list of values includes alternative security requirement objects that can be used.
88 -- Only one of the security requirement objects need to be satisfied to authorize a request.
89 -- Individual operations can override this definition.
90 -- To make security optional, an empty security requirement can be included in the array.
91 , _openApiSecurity :: [SecurityRequirement]
93 -- | A list of tags used by the specification with additional metadata.
94 -- The order of the tags can be used to reflect on their order by the parsing tools.
95 -- Not all tags that are used by the 'Operation' Object must be declared.
96 -- The tags that are not declared MAY be organized randomly or based on the tools' logic.
97 -- Each tag name in the list MUST be unique.
98 , _openApiTags :: InsOrdHashSet Tag
100 -- | Additional external documentation.
101 , _openApiExternalDocs :: Maybe ExternalDocs
102 } deriving (Eq, Show, Generic, Data, Typeable)
104-- | The object provides metadata about the API.
105-- The metadata MAY be used by the clients if needed,
106-- and MAY be presented in editing or documentation generation tools for convenience.
108 { -- | The title of the API.
111 -- | A short description of the API.
112 -- [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
113 , _infoDescription :: Maybe Text
115 -- | A URL to the Terms of Service for the API. MUST be in the format of a URL.
116 , _infoTermsOfService :: Maybe Text
118 -- | The contact information for the exposed API.
119 , _infoContact :: Maybe Contact
121 -- | The license information for the exposed API.
122 , _infoLicense :: Maybe License
124 -- | The version of the OpenAPI document (which is distinct from the
125 -- OpenAPI Specification version or the API implementation version).
126 , _infoVersion :: Text
127 } deriving (Eq, Show, Generic, Data, Typeable)
129-- | Contact information for the exposed API.
130data Contact = Contact
131 { -- | The identifying name of the contact person/organization.
132 _contactName :: Maybe Text
134 -- | The URL pointing to the contact information.
135 , _contactUrl :: Maybe URL
137 -- | The email address of the contact person/organization.
138 , _contactEmail :: Maybe Text
139 } deriving (Eq, Show, Generic, Data, Typeable)
141-- | License information for the exposed API.
142data License = License
143 { -- | The license name used for the API.
146 -- | A URL to the license used for the API.
147 , _licenseUrl :: Maybe URL
148 } deriving (Eq, Show, Generic, Data, Typeable)
150instance IsString License where
151 fromString s = License (fromString s) Nothing
153-- | An object representing a Server.
155 { -- | A URL to the target host. This URL supports Server Variables and MAY be relative,
156 -- to indicate that the host location is relative to the location where
157 -- the OpenAPI document is being served. Variable substitutions will be made when
158 -- a variable is named in @{brackets}@.
161 -- | An optional string describing the host designated by the URL.
162 -- [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
163 , _serverDescription :: Maybe Text
165 -- | A map between a variable name and its value.
166 -- The value is used for substitution in the server's URL template.
167 , _serverVariables :: InsOrdHashMap Text ServerVariable
168 } deriving (Eq, Show, Generic, Data, Typeable)
170data ServerVariable = ServerVariable
171 { -- | An enumeration of string values to be used if the substitution options
172 -- are from a limited set. The array SHOULD NOT be empty.
173 _serverVariableEnum :: Maybe (InsOrdHashSet Text) -- TODO NonEmpty
175 -- | The default value to use for substitution, which SHALL be sent if an alternate value
176 -- is not supplied. Note this behavior is different than the 'Schema\ Object's treatment
177 -- of default values, because in those cases parameter values are optional.
178 -- If the '_serverVariableEnum' is defined, the value SHOULD exist in the enum's values.
179 , _serverVariableDefault :: Text
181 -- | An optional description for the server variable.
182 -- [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
183 , _serverVariableDescription :: Maybe Text
184 } deriving (Eq, Show, Generic, Data, Typeable)
186instance IsString Server where
187 fromString s = Server (fromString s) Nothing mempty
189-- | Holds a set of reusable objects for different aspects of the OAS.
190-- All objects defined within the components object will have no effect on the API
191-- unless they are explicitly referenced from properties outside the components object.
192data Components = Components
193 { _componentsSchemas :: Definitions Schema
194 , _componentsResponses :: Definitions Response
195 , _componentsParameters :: Definitions Param
196 , _componentsExamples :: Definitions Example
197 , _componentsRequestBodies :: Definitions RequestBody
198 , _componentsHeaders :: Definitions Header
199 , _componentsSecuritySchemes :: Definitions SecurityScheme
200 , _componentsLinks :: Definitions Link
201 , _componentsCallbacks :: Definitions Callback
202 } deriving (Eq, Show, Generic, Data, Typeable)
204-- | Describes the operations available on a single path.
205-- A @'PathItem'@ may be empty, due to ACL constraints.
206-- The path itself is still exposed to the documentation viewer
207-- but they will not know which operations and parameters are available.
208data PathItem = PathItem
209 { -- | An optional, string summary, intended to apply to all operations in this path.
210 _pathItemSummary :: Maybe Text
212 -- | An optional, string description, intended to apply to all operations in this path.
213 -- [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
214 , _pathItemDescription :: Maybe Text
216 -- | A definition of a GET operation on this path.
217 , _pathItemGet :: Maybe Operation
219 -- | A definition of a PUT operation on this path.
220 , _pathItemPut :: Maybe Operation
222 -- | A definition of a POST operation on this path.
223 , _pathItemPost :: Maybe Operation
225 -- | A definition of a DELETE operation on this path.
226 , _pathItemDelete :: Maybe Operation
228 -- | A definition of a OPTIONS operation on this path.
229 , _pathItemOptions :: Maybe Operation
231 -- | A definition of a HEAD operation on this path.
232 , _pathItemHead :: Maybe Operation
234 -- | A definition of a PATCH operation on this path.
235 , _pathItemPatch :: Maybe Operation
237 -- | A definition of a TRACE operation on this path.
238 , _pathItemTrace :: Maybe Operation
240 -- | An alternative server array to service all operations in this path.
241 , _pathItemServers :: [Server]
243 -- | A list of parameters that are applicable for all the operations described under this path.
244 -- These parameters can be overridden at the operation level, but cannot be removed there.
245 -- The list MUST NOT include duplicated parameters.
246 -- A unique parameter is defined by a combination of a name and location.
247 , _pathItemParameters :: [Referenced Param]
248 } deriving (Eq, Show, Generic, Data, Typeable)
250-- | Describes a single API operation on a path.
251data Operation = Operation
252 { -- | A list of tags for API documentation control.
253 -- Tags can be used for logical grouping of operations by resources or any other qualifier.
254 _operationTags :: InsOrdHashSet TagName
256 -- | A short summary of what the operation does.
257 -- For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters.
258 , _operationSummary :: Maybe Text
260 -- | A verbose explanation of the operation behavior.
261 -- [CommonMark syntax](https://spec.commonmark.org/) can be used for rich text representation.
262 , _operationDescription :: Maybe Text
264 -- | Additional external documentation for this operation.
265 , _operationExternalDocs :: Maybe ExternalDocs
267 -- | Unique string used to identify the operation.
268 -- The id MUST be unique among all operations described in the API.
269 -- The operationId value is **case-sensitive**.
270 -- Tools and libraries MAY use the operationId to uniquely identify an operation, therefore,
271 -- it is RECOMMENDED to follow common programming naming conventions.
272 , _operationOperationId :: Maybe Text
274 -- | A list of parameters that are applicable for this operation.
275 -- If a parameter is already defined at the @'PathItem'@,
276 -- the new definition will override it, but can never remove it.
277 -- The list MUST NOT include duplicated parameters.
278 -- A unique parameter is defined by a combination of a name and location.
279 , _operationParameters :: [Referenced Param]
281 -- | The request body applicable for this operation.
282 -- The requestBody is only supported in HTTP methods where the HTTP 1.1
283 -- specification [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.3.1)
284 -- has explicitly defined semantics for request bodies.
285 -- In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers.
286 , _operationRequestBody :: Maybe (Referenced RequestBody)
288 -- | The list of possible responses as they are returned from executing this operation.
289 , _operationResponses :: Responses
291 -- | A map of possible out-of band callbacks related to the parent operation.
292 -- The key is a unique identifier for the 'Callback' Object.
293 -- Each value in the map is a 'Callback' Object that describes a request
294 -- that may be initiated by the API provider and the expected responses.
295 , _operationCallbacks :: InsOrdHashMap Text (Referenced Callback)
297 -- | Declares this operation to be deprecated.
298 -- Usage of the declared operation should be refrained.
299 -- Default value is @False@.
300 , _operationDeprecated :: Maybe Bool
302 -- | A declaration of which security schemes are applied for this operation.
303 -- The list of values describes alternative security schemes that can be used
304 -- (that is, there is a logical OR between the security requirements).
305 -- This definition overrides any declared top-level security.
306 -- To remove a top-level security declaration, @Just []@ can be used.
307 , _operationSecurity :: [SecurityRequirement]
309 -- | An alternative server array to service this operation.
310 -- If an alternative server object is specified at the 'PathItem' Object or Root level,
311 -- it will be overridden by this value.
312 , _operationServers :: [Server]
313 } deriving (Eq, Show, Generic, Data, Typeable)
315-- This instance should be in @http-media@.
316instance Data MediaType where
317 gunfold k z c = case constrIndex c of
318 1 -> k (k (k (z (\main sub params -> foldl (/:) (main // sub) (Map.toList params)))))
319 _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type MediaType."
321 toConstr _ = mediaTypeConstr
323 dataTypeOf _ = mediaTypeData
325mediaTypeConstr = mkConstr mediaTypeData "MediaType" [] Prefix
326mediaTypeData = mkDataType "MediaType" [mediaTypeConstr]
328instance Hashable MediaType where
329 hashWithSalt salt mt = salt `hashWithSalt` show mt
331-- | Describes a single request body.
332data RequestBody = RequestBody
333 { -- | A brief description of the request body. This could contain examples of use.
334 -- [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
335 _requestBodyDescription :: Maybe Text
337 -- | The content of the request body.
338 -- The key is a media type or media type range and the value describes it.
339 -- For requests that match multiple keys, only the most specific key is applicable.
340 -- e.g. @text/plain@ overrides @text/*@
341 , _requestBodyContent :: InsOrdHashMap MediaType MediaTypeObject
343 -- | Determines if the request body is required in the request.
344 -- Defaults to 'False'.
345 , _requestBodyRequired :: Maybe Bool
346 } deriving (Eq, Show, Generic, Data, Typeable)
348-- | Each Media Type Object provides schema and examples for the media type identified by its key.
349data MediaTypeObject = MediaTypeObject
350 { _mediaTypeObjectSchema :: Maybe (Referenced Schema)
352 -- | Example of the media type.
353 -- The example object SHOULD be in the correct format as specified by the media type.
354 , _mediaTypeObjectExample :: Maybe Value
356 -- | Examples of the media type.
357 -- Each example object SHOULD match the media type and specified schema if present.
358 , _mediaTypeObjectExamples :: InsOrdHashMap Text (Referenced Example)
360 -- | A map between a property name and its encoding information.
361 -- The key, being the property name, MUST exist in the schema as a property.
362 -- The encoding object SHALL only apply to 'RequestBody' objects when the media type
363 -- is @multipart@ or @application/x-www-form-urlencoded@.
364 , _mediaTypeObjectEncoding :: InsOrdHashMap Text Encoding
365 } deriving (Eq, Show, Generic, Data, Typeable)
367-- | In order to support common ways of serializing simple parameters, a set of style values are defined.
370 -- ^ Path-style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7).
372 -- ^ Label style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7).
374 -- ^ Form style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7).
375 -- This option replaces @collectionFormat@ with a @csv@ (when @explode@ is false) or @multi@
376 -- (when explode is true) value from OpenAPI 2.0.
378 -- ^ Simple style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7).
379 -- This option replaces @collectionFormat@ with a @csv@ value from OpenAPI 2.0.
380 | StyleSpaceDelimited
381 -- ^ Space separated array values.
382 -- This option replaces @collectionFormat@ equal to @ssv@ from OpenAPI 2.0.
384 -- ^ Pipe separated array values.
385 -- This option replaces @collectionFormat@ equal to @pipes@ from OpenAPI 2.0.
387 -- ^ Provides a simple way of rendering nested objects using form parameters.
388 deriving (Eq, Show, Generic, Data, Typeable)
390data Encoding = Encoding
391 { -- | The Content-Type for encoding a specific property.
392 -- Default value depends on the property type: for @string@
393 -- with format being @binary@ – @application/octet-stream@;
394 -- for other primitive types – @text/plain@; for object - @application/json@;
395 -- for array – the default is defined based on the inner type.
396 -- The value can be a specific media type (e.g. @application/json@),
397 -- a wildcard media type (e.g. @image/*@), or a comma-separated list of the two types.
398 _encodingContentType :: Maybe MediaType
400 -- | A map allowing additional information to be provided as headers,
401 -- for example @Content-Disposition@. @Content-Type@ is described separately
402 -- and SHALL be ignored in this section.
403 -- This property SHALL be ignored if the request body media type is not a @multipart@.
404 , _encodingHeaders :: InsOrdHashMap Text (Referenced Header)
406 -- | Describes how a specific property value will be serialized depending on its type.
407 -- See 'Param' Object for details on the style property.
408 -- The behavior follows the same values as query parameters, including default values.
409 -- This property SHALL be ignored if the request body media type
410 -- is not @application/x-www-form-urlencoded@.
411 , _encodingStyle :: Maybe Style
413 -- | When this is true, property values of type @array@ or @object@ generate
414 -- separate parameters for each value of the array,
415 -- or key-value-pair of the map.
416 -- For other types of properties this property has no effect.
417 -- When style is form, the default value is @true@. For all other styles,
418 -- the default value is @false@. This property SHALL be ignored
419 -- if the request body media type is not @application/x-www-form-urlencoded@.
420 , _encodingExplode :: Maybe Bool
422 -- | Determines whether the parameter value SHOULD allow reserved characters,
423 -- as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2)
424 -- @:/?#[]@!$&'()*+,;=@ to be included without percent-encoding.
425 -- The default value is @false@. This property SHALL be ignored if the request body media type
426 -- is not @application/x-www-form-urlencoded@.
427 , _encodingAllowReserved :: Maybe Bool
428 } deriving (Eq, Show, Generic, Data, Typeable)
430newtype MimeList = MimeList { getMimeList :: [MediaType] }
431 deriving (Eq, Show, Semigroup, Monoid, Typeable)
433mimeListConstr :: Constr
434mimeListConstr = mkConstr mimeListDataType "MimeList" ["getMimeList"] Prefix
436mimeListDataType :: DataType
437mimeListDataType = mkDataType "Data.OpenApi.MimeList" [mimeListConstr]
439instance Data MimeList where
440 gunfold k z c = case constrIndex c of
441 1 -> k (z (MimeList . map fromString))
442 _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type MimeList."
443 toConstr (MimeList _) = mimeListConstr
444 dataTypeOf _ = mimeListDataType
446-- | Describes a single operation parameter.
447-- A unique parameter is defined by a combination of a name and location.
449 { -- | The name of the parameter.
450 -- Parameter names are case sensitive.
453 -- | A brief description of the parameter.
454 -- This could contain examples of use.
455 -- CommonMark syntax MAY be used for rich text representation.
456 , _paramDescription :: Maybe Text
458 -- | Determines whether this parameter is mandatory.
459 -- If the parameter is in "path", this property is required and its value MUST be true.
460 -- Otherwise, the property MAY be included and its default value is @False@.
461 , _paramRequired :: Maybe Bool
463 -- | Specifies that a parameter is deprecated and SHOULD be transitioned out of usage.
464 -- Default value is @false@.
465 , _paramDeprecated :: Maybe Bool
467 -- | The location of the parameter.
468 , _paramIn :: ParamLocation
470 -- | Sets the ability to pass empty-valued parameters.
471 -- This is valid only for 'ParamQuery' parameters and allows sending
472 -- a parameter with an empty value. Default value is @false@.
473 , _paramAllowEmptyValue :: Maybe Bool
475 -- | Determines whether the parameter value SHOULD allow reserved characters,
476 -- as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2)
477 -- @:/?#[]@!$&'()*+,;=@ to be included without percent-encoding.
478 -- This property only applies to parameters with an '_paramIn' value of 'ParamQuery'.
479 -- The default value is 'False'.
480 , _paramAllowReserved :: Maybe Bool
482 -- | Parameter schema.
483 , _paramSchema :: Maybe (Referenced Schema)
485 -- | Describes how the parameter value will be serialized depending
486 -- on the type of the parameter value. Default values (based on value of '_paramIn'):
487 -- for 'ParamQuery' - 'StyleForm'; for 'ParamPath' - 'StyleSimple'; for 'ParamHeader' - 'StyleSimple';
488 -- for 'ParamCookie' - 'StyleForm'.
489 , _paramStyle :: Maybe Style
491 -- | When this is true, parameter values of type @array@ or @object@
492 -- generate separate parameters for each value of the array or key-value pair of the map.
493 -- For other types of parameters this property has no effect.
494 -- When style is @form@, the default value is true. For all other styles, the default value is false.
495 , _paramExplode :: Maybe Bool
497 -- | Example of the parameter's potential value.
498 -- The example SHOULD match the specified schema and encoding properties if present.
499 -- The '_paramExample' field is mutually exclusive of the '_paramExamples' field.
500 -- Furthermore, if referencing a schema that contains an example, the example value
501 -- SHALL override the example provided by the schema. To represent examples of media types
502 -- that cannot naturally be represented in JSON or YAML, a string value can contain
503 -- the example with escaping where necessary.
504 , _paramExample :: Maybe Value
506 -- | Examples of the parameter's potential value.
507 -- Each example SHOULD contain a value in the correct format as specified
508 -- in the parameter encoding. The '_paramExamples' field is mutually exclusive of the '_paramExample' field.
509 -- Furthermore, if referencing a schema that contains an example,
510 -- the examples value SHALL override the example provided by the schema.
511 , _paramExamples :: InsOrdHashMap Text (Referenced Example)
514 -- _paramContent :: InsOrdHashMap MediaType MediaTypeObject
515 -- should be singleton. mutually exclusive with _paramSchema.
516 } deriving (Eq, Show, Generic, Data, Typeable)
518data Example = Example
519 { -- | Short description for the example.
520 _exampleSummary :: Maybe Text
522 -- | Long description for the example.
523 -- CommonMark syntax MAY be used for rich text representation.
524 , _exampleDescription :: Maybe Text
526 -- | Embedded literal example.
527 -- The '_exampleValue' field and '_exampleExternalValue' field are mutually exclusive.
529 -- To represent examples of media types that cannot naturally represented in JSON or YAML,
530 -- use a string value to contain the example, escaping where necessary.
531 , _exampleValue :: Maybe Value
533 -- | A URL that points to the literal example.
534 -- This provides the capability to reference examples that cannot easily be included
535 -- in JSON or YAML documents. The '_exampleValue' field
536 -- and '_exampleExternalValue' field are mutually exclusive.
537 , _exampleExternalValue :: Maybe URL
538 } deriving (Eq, Show, Generic, Typeable, Data)
540data ExpressionOrValue
543 deriving (Eq, Show, Generic, Typeable, Data)
545-- | The Link object represents a possible design-time link for a response.
546-- The presence of a link does not guarantee the caller's ability to successfully invoke it,
547-- rather it provides a known relationship and traversal mechanism between responses and other operations.
549 { -- | A relative or absolute URI reference to an OAS operation.
550 -- This field is mutually exclusive of the '_linkOperationId' field,
551 -- and MUST point to an 'Operation' Object. Relative '_linkOperationRef'
552 -- values MAY be used to locate an existing 'Operation' Object in the OpenAPI definition.
553 _linkOperationRef :: Maybe Text
555 -- | The name of an /existing/, resolvable OAS operation, as defined with a unique
556 -- '_operationOperationId'. This field is mutually exclusive of the '_linkOperationRef' field.
557 , _linkOperationId :: Maybe Text
559 -- | A map representing parameters to pass to an operation as specified with '_linkOperationId'
560 -- or identified via '_linkOperationRef'. The key is the parameter name to be used, whereas
561 -- the value can be a constant or an expression to be evaluated and passed to the linked operation.
562 -- The parameter name can be qualified using the parameter location @[{in}.]{name}@
563 -- for operations that use the same parameter name in different locations (e.g. path.id).
564 , _linkParameters :: InsOrdHashMap Text ExpressionOrValue
566 -- | A literal value or @{expression}@ to use as a request body when calling the target operation.
567 , _linkRequestBody :: Maybe ExpressionOrValue
569 -- | A description of the link.
570 , _linkDescription :: Maybe Text
572 -- | A server object to be used by the target operation.
573 , _linkServer :: Maybe Server
574 } deriving (Eq, Show, Generic, Typeable, Data)
576-- | Items for @'OpenApiArray'@ schemas.
578-- __Warning__: OpenAPI 3.0 does not support tuple arrays. However, OpenAPI 3.1 will, as
579-- it will incorporate Json Schema mostly verbatim.
581-- @'OpenApiItemsObject'@ should be used to specify homogenous array @'Schema'@s.
583-- @'OpenApiItemsArray'@ should be used to specify tuple @'Schema'@s.
584data OpenApiItems where
585 OpenApiItemsObject :: Referenced Schema -> OpenApiItems
586 OpenApiItemsArray :: [Referenced Schema] -> OpenApiItems
587 deriving (Eq, Show, Typeable, Data)
589data OpenApiType where
590 OpenApiString :: OpenApiType
591 OpenApiNumber :: OpenApiType
592 OpenApiInteger :: OpenApiType
593 OpenApiBoolean :: OpenApiType
594 OpenApiArray :: OpenApiType
595 OpenApiNull :: OpenApiType
596 OpenApiObject :: OpenApiType
597 deriving (Eq, Show, Typeable, Generic, Data)
600 = -- | Parameters that are appended to the URL.
601 -- For example, in @/items?id=###@, the query parameter is @id@.
603 -- | Custom headers that are expected as part of the request.
605 -- | Used together with Path Templating, where the parameter value is actually part of the operation's URL.
606 -- This does not include the host or base path of the API.
607 -- For example, in @/items/{itemId}@, the path parameter is @itemId@.
609 -- | Used to pass a specific cookie value to the API.
611 deriving (Eq, Show, Generic, Data, Typeable)
618 { _schemaTitle :: Maybe Text
619 , _schemaDescription :: Maybe Text
620 , _schemaRequired :: [ParamName]
622 , _schemaNullable :: Maybe Bool
623 , _schemaAllOf :: Maybe [Referenced Schema]
624 , _schemaOneOf :: Maybe [Referenced Schema]
625 , _schemaNot :: Maybe (Referenced Schema)
626 , _schemaAnyOf :: Maybe [Referenced Schema]
627 , _schemaProperties :: InsOrdHashMap Text (Referenced Schema)
628 , _schemaAdditionalProperties :: Maybe AdditionalProperties
630 , _schemaDiscriminator :: Maybe Discriminator
631 , _schemaReadOnly :: Maybe Bool
632 , _schemaWriteOnly :: Maybe Bool
633 , _schemaXml :: Maybe Xml
634 , _schemaExternalDocs :: Maybe ExternalDocs
635 , _schemaExample :: Maybe Value
636 , _schemaDeprecated :: Maybe Bool
638 , _schemaMaxProperties :: Maybe Integer
639 , _schemaMinProperties :: Maybe Integer
641 , -- | Declares the value of the parameter that the server will use if none is provided,
642 -- for example a @"count"@ to control the number of results per page might default to @100@
643 -- if not supplied by the client in the request.
644 -- (Note: "default" has no meaning for required parameters.)
645 -- Unlike JSON Schema this value MUST conform to the defined type for this parameter.
646 _schemaDefault :: Maybe Value
648 , _schemaType :: Maybe OpenApiType
649 , _schemaFormat :: Maybe Format
650 , _schemaItems :: Maybe OpenApiItems
651 , _schemaMaximum :: Maybe Scientific
652 , _schemaExclusiveMaximum :: Maybe Bool
653 , _schemaMinimum :: Maybe Scientific
654 , _schemaExclusiveMinimum :: Maybe Bool
655 , _schemaMaxLength :: Maybe Integer
656 , _schemaMinLength :: Maybe Integer
657 , _schemaPattern :: Maybe Pattern
658 , _schemaMaxItems :: Maybe Integer
659 , _schemaMinItems :: Maybe Integer
660 , _schemaUniqueItems :: Maybe Bool
661 , _schemaEnum :: Maybe [Value]
662 , _schemaMultipleOf :: Maybe Scientific
663 } deriving (Eq, Show, Generic, Data, Typeable)
665-- | Regex pattern for @string@ type.
668data Discriminator = Discriminator
669 { -- | The name of the property in the payload that will hold the discriminator value.
670 _discriminatorPropertyName :: Text
672 -- | An object to hold mappings between payload values and schema names or references.
673 , _discriminatorMapping :: InsOrdHashMap Text Text
674 } deriving (Eq, Show, Generic, Data, Typeable)
676-- | A @'Schema'@ with an optional name.
677-- This name can be used in references.
678data NamedSchema = NamedSchema
679 { _namedSchemaName :: Maybe Text
680 , _namedSchemaSchema :: Schema
681 } deriving (Eq, Show, Generic, Data, Typeable)
684 { -- | Replaces the name of the element/attribute used for the described schema property.
685 -- When defined within the @'OpenApiItems'@ (items), it will affect the name of the individual XML elements within the list.
686 -- When defined alongside type being array (outside the items),
687 -- it will affect the wrapping element and only if wrapped is true.
688 -- If wrapped is false, it will be ignored.
689 _xmlName :: Maybe Text
691 -- | The URL of the namespace definition.
692 -- Value SHOULD be in the form of a URL.
693 , _xmlNamespace :: Maybe Text
695 -- | The prefix to be used for the name.
696 , _xmlPrefix :: Maybe Text
698 -- | Declares whether the property definition translates to an attribute instead of an element.
699 -- Default value is @False@.
700 , _xmlAttribute :: Maybe Bool
702 -- | MAY be used only for an array definition.
703 -- Signifies whether the array is wrapped
704 -- (for example, @\<books\>\<book/\>\<book/\>\</books\>@)
705 -- or unwrapped (@\<book/\>\<book/\>@).
706 -- Default value is @False@.
707 -- The definition takes effect only when defined alongside type being array (outside the items).
708 , _xmlWrapped :: Maybe Bool
709 } deriving (Eq, Show, Generic, Data, Typeable)
711-- | A container for the expected responses of an operation.
712-- The container maps a HTTP response code to the expected response.
713-- It is not expected from the documentation to necessarily cover all possible HTTP response codes,
714-- since they may not be known in advance.
715-- However, it is expected from the documentation to cover a successful operation response and any known errors.
716data Responses = Responses
717 { -- | The documentation of responses other than the ones declared for specific HTTP response codes.
718 -- It can be used to cover undeclared responses.
719 _responsesDefault :: Maybe (Referenced Response)
721 -- | Any HTTP status code can be used as the property name (one property per HTTP status code).
722 -- Describes the expected response for those HTTP status codes.
723 , _responsesResponses :: InsOrdHashMap HttpStatusCode (Referenced Response)
724 } deriving (Eq, Show, Generic, Data, Typeable)
726type HttpStatusCode = Int
728-- | Describes a single response from an API Operation.
729data Response = Response
730 { -- | A short description of the response.
731 -- [CommonMark syntax](https://spec.commonmark.org/) can be used for rich text representation.
732 _responseDescription :: Text
734 -- | A map containing descriptions of potential response payloads.
735 -- The key is a media type or media type range and the value describes it.
736 -- For responses that match multiple keys, only the most specific key is applicable.
737 -- e.g. @text/plain@ overrides @text/*@.
738 , _responseContent :: InsOrdHashMap MediaType MediaTypeObject
740 -- | Maps a header name to its definition.
741 , _responseHeaders :: InsOrdHashMap HeaderName (Referenced Header)
743 -- | A map of operations links that can be followed from the response.
744 -- The key of the map is a short name for the link, following the naming
745 -- constraints of the names for 'Component' Objects.
746 , _responseLinks :: InsOrdHashMap Text (Referenced Link)
747 } deriving (Eq, Show, Generic, Data, Typeable)
749instance IsString Response where
750 fromString s = Response (fromString s) mempty mempty mempty
752-- | A map of possible out-of band callbacks related to the parent operation.
753-- Each value in the map is a 'PathItem' Object that describes a set of requests that
754-- may be initiated by the API provider and the expected responses.
755-- The key value used to identify the path item object is an expression, evaluated at runtime,
756-- that identifies a URL to use for the callback operation.
757newtype Callback = Callback (InsOrdHashMap Text PathItem)
758 deriving (Eq, Show, Generic, Data, Typeable)
760type HeaderName = Text
762-- | Header fields have the same meaning as for 'Param'.
764-- Style is always treated as 'StyleSimple', as it is the only value allowed for headers.
766 { -- | A short description of the header.
767 _headerDescription :: Maybe HeaderName
769 , _headerRequired :: Maybe Bool
770 , _headerDeprecated :: Maybe Bool
771 , _headerAllowEmptyValue :: Maybe Bool
772 , _headerExplode :: Maybe Bool
773 , _headerExample :: Maybe Value
774 , _headerExamples :: InsOrdHashMap Text (Referenced Example)
776 , _headerSchema :: Maybe (Referenced Schema)
777 } deriving (Eq, Show, Generic, Data, Typeable)
779-- | According to RFC7235
791 deriving (Eq, Show, Generic, Data, Typeable)
793-- | The location of the API key.
798 deriving (Eq, Show, Generic, Data, Typeable)
800data ApiKeyParams = ApiKeyParams
801 { -- | The name of the header or query parameter to be used.
804 -- | The location of the API key.
805 , _apiKeyIn :: ApiKeyLocation
806 } deriving (Eq, Show, Generic, Data, Typeable)
808-- | The authorization URL to be used for OAuth2 flow. This SHOULD be in the form of a URL.
809type AuthorizationURL = Text
811-- | The token URL to be used for OAuth2 flow. This SHOULD be in the form of a URL.
814newtype OAuth2ImplicitFlow
815 = OAuth2ImplicitFlow {_oAuth2ImplicitFlowAuthorizationUrl :: AuthorizationURL}
816 deriving (Eq, Show, Generic, Data, Typeable)
818newtype OAuth2PasswordFlow
819 = OAuth2PasswordFlow {_oAuth2PasswordFlowTokenUrl :: TokenURL}
820 deriving (Eq, Show, Generic, Data, Typeable)
822newtype OAuth2ClientCredentialsFlow
823 = OAuth2ClientCredentialsFlow {_oAuth2ClientCredentialsFlowTokenUrl :: TokenURL}
824 deriving (Eq, Show, Generic, Data, Typeable)
826data OAuth2AuthorizationCodeFlow = OAuth2AuthorizationCodeFlow
827 { _oAuth2AuthorizationCodeFlowAuthorizationUrl :: AuthorizationURL
828 , _oAuth2AuthorizationCodeFlowTokenUrl :: TokenURL
829 } deriving (Eq, Show, Generic, Data, Typeable)
831data OAuth2Flow p = OAuth2Flow
834 -- | The URL to be used for obtaining refresh tokens.
835 , _oAath2RefreshUrl :: Maybe URL
837 -- | The available scopes for the OAuth2 security scheme.
838 -- A map between the scope name and a short description for it.
839 -- The map MAY be empty.
840 , _oAuth2Scopes :: InsOrdHashMap Text Text
841 } deriving (Eq, Show, Generic, Data, Typeable)
843data OAuth2Flows = OAuth2Flows
844 { -- | Configuration for the OAuth Implicit flow
845 _oAuth2FlowsImplicit :: Maybe (OAuth2Flow OAuth2ImplicitFlow)
847 -- | Configuration for the OAuth Resource Owner Password flow
848 , _oAuth2FlowsPassword :: Maybe (OAuth2Flow OAuth2PasswordFlow)
850 -- | Configuration for the OAuth Client Credentials flow
851 , _oAuth2FlowsClientCredentials :: Maybe (OAuth2Flow OAuth2ClientCredentialsFlow)
853 -- | Configuration for the OAuth Authorization Code flow
854 , _oAuth2FlowsAuthorizationCode :: Maybe (OAuth2Flow OAuth2AuthorizationCodeFlow)
855 } deriving (Eq, Show, Generic, Data, Typeable)
857data SecuritySchemeType
858 = SecuritySchemeHttp HttpScheme
859 | SecuritySchemeApiKey ApiKeyParams
860 | SecuritySchemeOAuth2 OAuth2Flows
861 | SecuritySchemeOpenIdConnect URL
862 deriving (Eq, Show, Generic, Data, Typeable)
864data SecurityScheme = SecurityScheme
865 { -- | The type of the security scheme.
866 _securitySchemeType :: SecuritySchemeType
868 -- | A short description for security scheme.
869 , _securitySchemeDescription :: Maybe Text
870 } deriving (Eq, Show, Generic, Data, Typeable)
872newtype SecurityDefinitions
873 = SecurityDefinitions (Definitions SecurityScheme)
874 deriving (Eq, Show, Generic, Data, Typeable)
876-- | Lists the required security schemes to execute this operation.
877-- The object can have multiple security schemes declared in it which are all required
878-- (that is, there is a logical AND between the schemes).
879newtype SecurityRequirement = SecurityRequirement
880 { getSecurityRequirement :: InsOrdHashMap Text [Text]
881 } deriving (Eq, Read, Show, Semigroup, Monoid, ToJSON, FromJSON, Data, Typeable)
886-- | Allows adding meta data to a single tag that is used by @Operation@.
887-- It is not mandatory to have a @Tag@ per tag used there.
889 { -- | The name of the tag.
892 -- | A short description for the tag.
893 -- [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
894 , _tagDescription :: Maybe Text
896 -- | Additional external documentation for this tag.
897 , _tagExternalDocs :: Maybe ExternalDocs
898 } deriving (Eq, Ord, Show, Generic, Data, Typeable)
902instance IsString Tag where
903 fromString s = Tag (fromString s) Nothing Nothing
905-- | Allows referencing an external resource for extended documentation.
906data ExternalDocs = ExternalDocs
907 { -- | A short description of the target documentation.
908 -- [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
909 _externalDocsDescription :: Maybe Text
911 -- | The URL for the target documentation.
912 , _externalDocsUrl :: URL
913 } deriving (Eq, Ord, Show, Generic, Data, Typeable)
915instance Hashable ExternalDocs
917-- | A simple object to allow referencing other definitions in the specification.
918-- It can be used to reference parameters and responses that are defined at the top level for reuse.
919newtype Reference = Reference { getReference :: Text }
920 deriving (Eq, Show, Data, Typeable)
925 deriving (Eq, Show, Functor, Data, Typeable)
927instance IsString a => IsString (Referenced a) where
928 fromString = Inline . fromString
930newtype URL = URL { getUrl :: Text } deriving (Eq, Ord, Show, Hashable, ToJSON, FromJSON, Data, Typeable)
932data AdditionalProperties
933 = AdditionalPropertiesAllowed Bool
934 | AdditionalPropertiesSchema (Referenced Schema)
935 deriving (Eq, Show, Data, Typeable)
937-------------------------------------------------------------------------------
939-------------------------------------------------------------------------------
941deriveGeneric ''Server
942deriveGeneric ''Components
943deriveGeneric ''Header
944deriveGeneric ''OAuth2Flow
945deriveGeneric ''OAuth2Flows
946deriveGeneric ''Operation
948deriveGeneric ''PathItem
949deriveGeneric ''Response
950deriveGeneric ''RequestBody
951deriveGeneric ''MediaTypeObject
952deriveGeneric ''Responses
953deriveGeneric ''SecurityScheme
954deriveGeneric ''Schema
955deriveGeneric ''OpenApi
956deriveGeneric ''Example
957deriveGeneric ''Encoding
960-- =======================================================================
962-- =======================================================================
964instance Semigroup OpenApi where
965 (<>) = genericMappend
966instance Monoid OpenApi where
967 mempty = genericMempty
970instance Semigroup Info where
971 (<>) = genericMappend
972instance Monoid Info where
973 mempty = genericMempty
976instance Semigroup Contact where
977 (<>) = genericMappend
978instance Monoid Contact where
979 mempty = genericMempty
982instance Semigroup Components where
983 (<>) = genericMappend
984instance Monoid Components where
985 mempty = genericMempty
988instance Semigroup PathItem where
989 (<>) = genericMappend
990instance Monoid PathItem where
991 mempty = genericMempty
994instance Semigroup Schema where
995 (<>) = genericMappend
996instance Monoid Schema where
997 mempty = genericMempty
1000instance Semigroup Param where
1001 (<>) = genericMappend
1002instance Monoid Param where
1003 mempty = genericMempty
1006instance Semigroup Header where
1007 (<>) = genericMappend
1008instance Monoid Header where
1009 mempty = genericMempty
1012instance Semigroup Responses where
1013 (<>) = genericMappend
1014instance Monoid Responses where
1015 mempty = genericMempty
1018instance Semigroup Response where
1019 (<>) = genericMappend
1020instance Monoid Response where
1021 mempty = genericMempty
1024instance Semigroup MediaTypeObject where
1025 (<>) = genericMappend
1026instance Monoid MediaTypeObject where
1027 mempty = genericMempty
1030instance Semigroup Encoding where
1031 (<>) = genericMappend
1032instance Monoid Encoding where
1033 mempty = genericMempty
1036instance Semigroup ExternalDocs where
1037 (<>) = genericMappend
1038instance Monoid ExternalDocs where
1039 mempty = genericMempty
1042instance Semigroup Operation where
1043 (<>) = genericMappend
1044instance Monoid Operation where
1045 mempty = genericMempty
1048instance Semigroup (OAuth2Flow p) where
1049 l@OAuth2Flow{ _oAath2RefreshUrl = lUrl, _oAuth2Scopes = lScopes }
1050 <> OAuth2Flow { _oAath2RefreshUrl = rUrl, _oAuth2Scopes = rScopes } =
1051 l { _oAath2RefreshUrl = swaggerMappend lUrl rUrl, _oAuth2Scopes = lScopes <> rScopes }
1053-- swaggerMappend has First-like semantics, and here we need mappend'ing under Maybes.
1054instance Semigroup OAuth2Flows where
1055 l <> r = OAuth2Flows
1056 { _oAuth2FlowsImplicit = _oAuth2FlowsImplicit l <> _oAuth2FlowsImplicit r
1057 , _oAuth2FlowsPassword = _oAuth2FlowsPassword l <> _oAuth2FlowsPassword r
1058 , _oAuth2FlowsClientCredentials = _oAuth2FlowsClientCredentials l <> _oAuth2FlowsClientCredentials r
1059 , _oAuth2FlowsAuthorizationCode = _oAuth2FlowsAuthorizationCode l <> _oAuth2FlowsAuthorizationCode r
1062instance Monoid OAuth2Flows where
1063 mempty = genericMempty
1066instance Semigroup SecurityScheme where
1067 SecurityScheme (SecuritySchemeOAuth2 lFlows) lDesc
1068 <> SecurityScheme (SecuritySchemeOAuth2 rFlows) rDesc =
1069 SecurityScheme (SecuritySchemeOAuth2 $ lFlows <> rFlows) (swaggerMappend lDesc rDesc)
1072instance Semigroup SecurityDefinitions where
1073 (SecurityDefinitions sd1) <> (SecurityDefinitions sd2) =
1074 SecurityDefinitions $ InsOrdHashMap.unionWith (<>) sd1 sd2
1076instance Monoid SecurityDefinitions where
1077 mempty = SecurityDefinitions InsOrdHashMap.empty
1080instance Semigroup RequestBody where
1081 (<>) = genericMappend
1082instance Monoid RequestBody where
1083 mempty = genericMempty
1086-- =======================================================================
1087-- SwaggerMonoid helper instances
1088-- =======================================================================
1090instance SwaggerMonoid Info
1091instance SwaggerMonoid Components
1092instance SwaggerMonoid PathItem
1093instance SwaggerMonoid Schema
1094instance SwaggerMonoid Param
1095instance SwaggerMonoid Responses
1096instance SwaggerMonoid Response
1097instance SwaggerMonoid ExternalDocs
1098instance SwaggerMonoid Operation
1099instance (Eq a, Hashable a) => SwaggerMonoid (InsOrdHashSet a)
1101instance SwaggerMonoid MimeList
1102deriving instance SwaggerMonoid URL
1104instance SwaggerMonoid OpenApiType where
1105 swaggerMempty = OpenApiString
1106 swaggerMappend _ y = y
1108instance SwaggerMonoid ParamLocation where
1109 swaggerMempty = ParamQuery
1110 swaggerMappend _ y = y
1112instance {-# OVERLAPPING #-} SwaggerMonoid (InsOrdHashMap FilePath PathItem) where
1113 swaggerMempty = InsOrdHashMap.empty
1114 swaggerMappend = InsOrdHashMap.unionWith mappend
1116instance Monoid a => SwaggerMonoid (Referenced a) where
1117 swaggerMempty = Inline mempty
1118 swaggerMappend (Inline x) (Inline y) = Inline (mappend x y)
1119 swaggerMappend _ y = y
1121-- =======================================================================
1122-- Simple Generic-based ToJSON instances
1123-- =======================================================================
1125instance ToJSON Style where
1126 toJSON = genericToJSON (jsonPrefix "Style")
1128instance ToJSON OpenApiType where
1129 toJSON = genericToJSON (jsonPrefix "Swagger")
1131instance ToJSON ParamLocation where
1132 toJSON = genericToJSON (jsonPrefix "Param")
1134instance ToJSON Info where
1135 toJSON = genericToJSON (jsonPrefix "Info")
1137instance ToJSON Contact where
1138 toJSON = genericToJSON (jsonPrefix "Contact")
1140instance ToJSON License where
1141 toJSON = genericToJSON (jsonPrefix "License")
1143instance ToJSON ServerVariable where
1144 toJSON = genericToJSON (jsonPrefix "ServerVariable")
1146instance ToJSON HttpScheme where
1147 toJSON scheme = case scheme of
1148 SCRAM_SHA_1 -> "SCRAM-SHA-1"
1149 SCRAM_SHA_256 -> "SCRAM-SHA-256"
1151 other -> genericToJSON defaultOptions other
1153instance ToJSON ApiKeyLocation where
1154 toJSON = genericToJSON (jsonPrefix "ApiKey")
1156instance ToJSON ApiKeyParams where
1157 toJSON = genericToJSON (jsonPrefix "apiKey")
1159instance ToJSON Tag where
1160 toJSON = genericToJSON (jsonPrefix "Tag")
1162instance ToJSON ExternalDocs where
1163 toJSON = genericToJSON (jsonPrefix "ExternalDocs")
1165instance ToJSON Xml where
1166 toJSON = genericToJSON (jsonPrefix "Xml")
1168instance ToJSON Discriminator where
1169 toJSON = genericToJSON (jsonPrefix "Discriminator")
1171instance ToJSON OAuth2ImplicitFlow where
1172 toJSON = genericToJSON (jsonPrefix "OAuth2ImplicitFlow")
1174instance ToJSON OAuth2PasswordFlow where
1175 toJSON = genericToJSON (jsonPrefix "OAuth2PasswordFlow")
1177instance ToJSON OAuth2ClientCredentialsFlow where
1178 toJSON = genericToJSON (jsonPrefix "OAuth2ClientCredentialsFlow")
1180instance ToJSON OAuth2AuthorizationCodeFlow where
1181 toJSON = genericToJSON (jsonPrefix "OAuth2AuthorizationCodeFlow")
1183-- =======================================================================
1184-- Simple Generic-based FromJSON instances
1185-- =======================================================================
1187instance FromJSON Style where
1188 parseJSON = genericParseJSON (jsonPrefix "Style")
1190instance FromJSON OpenApiType where
1191 parseJSON = genericParseJSON (jsonPrefix "Swagger")
1193instance FromJSON ParamLocation where
1194 parseJSON = genericParseJSON (jsonPrefix "Param")
1196instance FromJSON Info where
1197 parseJSON = genericParseJSON (jsonPrefix "Info")
1199instance FromJSON Contact where
1200 parseJSON = genericParseJSON (jsonPrefix "Contact")
1202instance FromJSON License where
1203 parseJSON = genericParseJSON (jsonPrefix "License")
1205instance FromJSON ServerVariable where
1206 parseJSON = genericParseJSON (jsonPrefix "ServerVariable")
1208instance FromJSON HttpScheme where
1209 parseJSON = withText "HttpScheme" $ \txt -> case txt of
1210 "SCRAM-SHA-1" -> pure SCRAM_SHA_1
1211 "SCRAM-SHA-256" -> pure SCRAM_SHA_256
1212 "vapid" -> pure Vapid
1213 _ -> genericParseJSON defaultOptions $ String txt
1215instance FromJSON ApiKeyLocation where
1216 parseJSON = genericParseJSON (jsonPrefix "ApiKey")
1218instance FromJSON ApiKeyParams where
1219 parseJSON = genericParseJSON (jsonPrefix "apiKey")
1221instance FromJSON Tag where
1222 parseJSON = genericParseJSON (jsonPrefix "Tag")
1224instance FromJSON ExternalDocs where
1225 parseJSON = genericParseJSON (jsonPrefix "ExternalDocs")
1227instance FromJSON Discriminator where
1228 parseJSON = genericParseJSON (jsonPrefix "Discriminator")
1230instance FromJSON OAuth2ImplicitFlow where
1231 parseJSON = genericParseJSON (jsonPrefix "OAuth2ImplicitFlow")
1233instance FromJSON OAuth2PasswordFlow where
1234 parseJSON = genericParseJSON (jsonPrefix "OAuth2PasswordFlow")
1236instance FromJSON OAuth2ClientCredentialsFlow where
1237 parseJSON = genericParseJSON (jsonPrefix "OAuth2ClientCredentialsFlow")
1239instance FromJSON OAuth2AuthorizationCodeFlow where
1240 parseJSON = genericParseJSON (jsonPrefix "OAuth2AuthorizationCodeFlow")
1242-- =======================================================================
1243-- Manual ToJSON instances
1244-- =======================================================================
1246instance ToJSON MediaType where
1247 toJSON = toJSON . show
1248 toEncoding = toEncoding . show
1250instance ToJSONKey MediaType where
1251 toJSONKey = JSON.toJSONKeyText (Text.pack . show)
1253instance (Eq p, ToJSON p, AesonDefaultValue p) => ToJSON (OAuth2Flow p) where
1254 toJSON = sopSwaggerGenericToJSON
1255 toEncoding = sopSwaggerGenericToEncoding
1257instance ToJSON OAuth2Flows where
1258 toJSON = sopSwaggerGenericToJSON
1259 toEncoding = sopSwaggerGenericToEncoding
1261instance ToJSON SecuritySchemeType where
1262 toJSON (SecuritySchemeHttp scheme)
1263 = object [ "type" .= ("http" :: Text), "scheme" .= toJSON scheme ]
1264 toJSON (SecuritySchemeApiKey params)
1266 <+> object [ "type" .= ("apiKey" :: Text) ]
1267 toJSON (SecuritySchemeOAuth2 params) = object
1268 [ "type" .= ("oauth2" :: Text)
1269 , "flows" .= toJSON params
1271 toJSON (SecuritySchemeOpenIdConnect url) = object
1272 [ "type" .= ("openIdConnect" :: Text)
1273 , "openIdConnectUrl" .= url
1276instance ToJSON OpenApi where
1277 toJSON a = sopSwaggerGenericToJSON a &
1278 if InsOrdHashMap.null (_openApiPaths a)
1279 then (<+> object ["paths" .= object []])
1281 toEncoding = sopSwaggerGenericToEncoding
1283instance ToJSON Server where
1284 toJSON = sopSwaggerGenericToJSON
1285 toEncoding = sopSwaggerGenericToEncoding
1287instance ToJSON SecurityScheme where
1288 toJSON = sopSwaggerGenericToJSON
1289 toEncoding = sopSwaggerGenericToEncoding
1291instance ToJSON Schema where
1292 toJSON = sopSwaggerGenericToJSONWithOpts $
1293 mkSwaggerAesonOptions "schema" & saoSubObject ?~ "items"
1295instance ToJSON Header where
1296 toJSON = sopSwaggerGenericToJSON
1297 toEncoding = sopSwaggerGenericToEncoding
1299-- | As for nullary schema for 0-arity type constructors, see
1300-- <https://github.com/GetShopTV/swagger2/issues/167>.
1302-- >>> encode (OpenApiItemsArray [])
1303-- "{\"example\":[],\"items\":{},\"maxItems\":0}"
1305instance ToJSON OpenApiItems where
1306 toJSON (OpenApiItemsObject x) = object [ "items" .= x ]
1307 toJSON (OpenApiItemsArray []) = object
1308 [ "items" .= object []
1309 , "maxItems" .= (0 :: Int)
1310 , "example" .= Array mempty
1312 toJSON (OpenApiItemsArray x) = object [ "items" .= x ]
1314instance ToJSON Components where
1315 toJSON = sopSwaggerGenericToJSON
1316 toEncoding = sopSwaggerGenericToEncoding
1318instance ToJSON MimeList where
1319 toJSON (MimeList xs) = toJSON (map show xs)
1321instance ToJSON Param where
1322 toJSON = sopSwaggerGenericToJSON
1323 toEncoding = sopSwaggerGenericToEncoding
1325instance ToJSON Responses where
1326 toJSON = sopSwaggerGenericToJSON
1327 toEncoding = sopSwaggerGenericToEncoding
1329instance ToJSON Response where
1330 toJSON = sopSwaggerGenericToJSON
1331 toEncoding = sopSwaggerGenericToEncoding
1333instance ToJSON Operation where
1334 toJSON = sopSwaggerGenericToJSON
1335 toEncoding = sopSwaggerGenericToEncoding
1337instance ToJSON PathItem where
1338 toJSON = sopSwaggerGenericToJSON
1339 toEncoding = sopSwaggerGenericToEncoding
1341instance ToJSON RequestBody where
1342 toJSON = sopSwaggerGenericToJSON
1343 toEncoding = sopSwaggerGenericToEncoding
1345instance ToJSON MediaTypeObject where
1346 toJSON = sopSwaggerGenericToJSON
1347 toEncoding = sopSwaggerGenericToEncoding
1349instance ToJSON Example where
1350 toJSON = sopSwaggerGenericToJSON
1351 toEncoding = sopSwaggerGenericToEncoding
1353instance ToJSON Encoding where
1354 toJSON = sopSwaggerGenericToJSON
1355 toEncoding = sopSwaggerGenericToEncoding
1357instance ToJSON Link where
1358 toJSON = sopSwaggerGenericToJSON
1359 toEncoding = sopSwaggerGenericToEncoding
1361instance ToJSON SecurityDefinitions where
1362 toJSON (SecurityDefinitions sd) = toJSON sd
1364instance ToJSON Reference where
1365 toJSON (Reference ref) = object [ "$ref" .= ref ]
1367referencedToJSON :: ToJSON a => Text -> Referenced a -> Value
1368referencedToJSON prefix (Ref (Reference ref)) = object [ "$ref" .= (prefix <> ref) ]
1369referencedToJSON _ (Inline x) = toJSON x
1371instance ToJSON (Referenced Schema) where toJSON = referencedToJSON "#/components/schemas/"
1372instance ToJSON (Referenced Param) where toJSON = referencedToJSON "#/components/parameters/"
1373instance ToJSON (Referenced Response) where toJSON = referencedToJSON "#/components/responses/"
1374instance ToJSON (Referenced RequestBody) where toJSON = referencedToJSON "#/components/requestBodies/"
1375instance ToJSON (Referenced Example) where toJSON = referencedToJSON "#/components/examples/"
1376instance ToJSON (Referenced Header) where toJSON = referencedToJSON "#/components/headers/"
1377instance ToJSON (Referenced Link) where toJSON = referencedToJSON "#/components/links/"
1378instance ToJSON (Referenced Callback) where toJSON = referencedToJSON "#/components/callbacks/"
1380instance ToJSON AdditionalProperties where
1381 toJSON (AdditionalPropertiesAllowed b) = toJSON b
1382 toJSON (AdditionalPropertiesSchema s) = toJSON s
1384instance ToJSON ExpressionOrValue where
1385 toJSON (Expression expr) = toJSON expr
1386 toJSON (Value val) = toJSON val
1388instance ToJSON Callback where
1389 toJSON (Callback ps) = toJSON ps
1391-- =======================================================================
1392-- Manual FromJSON instances
1393-- =======================================================================
1395instance FromJSON MediaType where
1396 parseJSON = withText "MediaType" $ \str ->
1397 maybe (fail $ "Invalid media type literal " <> Text.unpack str) pure $ parseAccept $ encodeUtf8 str
1399instance FromJSONKey MediaType where
1400 fromJSONKey = FromJSONKeyTextParser (parseJSON . String)
1402instance (Eq p, FromJSON p, AesonDefaultValue p) => FromJSON (OAuth2Flow p) where
1403 parseJSON = sopSwaggerGenericParseJSON
1405instance FromJSON OAuth2Flows where
1406 parseJSON = sopSwaggerGenericParseJSON
1408instance FromJSON SecuritySchemeType where
1409 parseJSON js@(Object o) = do
1410 (t :: Text) <- o .: "type"
1412 "http" -> SecuritySchemeHttp <$> o .: "scheme"
1413 "apiKey" -> SecuritySchemeApiKey <$> parseJSON js
1414 "oauth2" -> SecuritySchemeOAuth2 <$> (o .: "flows")
1415 "openIdConnect" -> SecuritySchemeOpenIdConnect <$> (o .: "openIdConnectUrl")
1419instance FromJSON OpenApi where
1420 parseJSON = sopSwaggerGenericParseJSON
1422instance FromJSON Server where
1423 parseJSON = sopSwaggerGenericParseJSON
1425instance FromJSON SecurityScheme where
1426 parseJSON = sopSwaggerGenericParseJSON
1428instance FromJSON Schema where
1429 parseJSON = fmap nullaryCleanup . sopSwaggerGenericParseJSON
1430 where nullaryCleanup :: Schema -> Schema
1432 if _schemaItems s == Just (OpenApiItemsArray [])
1433 then s { _schemaExample = Nothing
1434 , _schemaMaxItems = Nothing
1438instance FromJSON Header where
1439 parseJSON = sopSwaggerGenericParseJSON
1441instance FromJSON OpenApiItems where
1442 parseJSON js@(Object obj)
1443 | null obj = pure $ OpenApiItemsArray [] -- Nullary schema.
1444 | otherwise = OpenApiItemsObject <$> parseJSON js
1445 parseJSON js@(Array _) = OpenApiItemsArray <$> parseJSON js
1448instance FromJSON Components where
1449 parseJSON = sopSwaggerGenericParseJSON
1451instance FromJSON MimeList where
1452 parseJSON js = MimeList . map fromString <$> parseJSON js
1454instance FromJSON Param where
1455 parseJSON = sopSwaggerGenericParseJSON
1457instance FromJSON Responses where
1458 parseJSON (Object o) = Responses
1460 <*> parseJSON (Object (HashMap.delete "default" o))
1463instance FromJSON Example where
1464 parseJSON = sopSwaggerGenericParseJSON
1466instance FromJSON Response where
1467 parseJSON = sopSwaggerGenericParseJSON
1469instance FromJSON Operation where
1470 parseJSON = sopSwaggerGenericParseJSON
1472instance FromJSON PathItem where
1473 parseJSON = sopSwaggerGenericParseJSON
1475instance FromJSON SecurityDefinitions where
1476 parseJSON js = SecurityDefinitions <$> parseJSON js
1478instance FromJSON RequestBody where
1479 parseJSON = sopSwaggerGenericParseJSON
1481instance FromJSON MediaTypeObject where
1482 parseJSON = sopSwaggerGenericParseJSON
1484instance FromJSON Encoding where
1485 parseJSON = sopSwaggerGenericParseJSON
1487instance FromJSON Link where
1488 parseJSON = sopSwaggerGenericParseJSON
1490instance FromJSON Reference where
1491 parseJSON (Object o) = Reference <$> o .: "$ref"
1494referencedParseJSON :: FromJSON a => Text -> Value -> JSON.Parser (Referenced a)
1495referencedParseJSON prefix js@(Object o) = do
1498 Nothing -> Inline <$> parseJSON js
1499 Just s -> Ref <$> parseRef s
1502 case Text.stripPrefix prefix s of
1503 Nothing -> fail $ "expected $ref of the form \"" <> Text.unpack prefix <> "*\", but got " <> show s
1504 Just suffix -> pure (Reference suffix)
1505referencedParseJSON _ _ = fail "referenceParseJSON: not an object"
1507instance FromJSON (Referenced Schema) where parseJSON = referencedParseJSON "#/components/schemas/"
1508instance FromJSON (Referenced Param) where parseJSON = referencedParseJSON "#/components/parameters/"
1509instance FromJSON (Referenced Response) where parseJSON = referencedParseJSON "#/components/responses/"
1510instance FromJSON (Referenced RequestBody) where parseJSON = referencedParseJSON "#/components/requestBodies/"
1511instance FromJSON (Referenced Example) where parseJSON = referencedParseJSON "#/components/examples/"
1512instance FromJSON (Referenced Header) where parseJSON = referencedParseJSON "#/components/headers/"
1513instance FromJSON (Referenced Link) where parseJSON = referencedParseJSON "#/components/links/"
1514instance FromJSON (Referenced Callback) where parseJSON = referencedParseJSON "#/components/callbacks/"
1516instance FromJSON Xml where
1517 parseJSON = genericParseJSON (jsonPrefix "xml")
1519instance FromJSON AdditionalProperties where
1520 parseJSON (Bool b) = pure $ AdditionalPropertiesAllowed b
1521 parseJSON js = AdditionalPropertiesSchema <$> parseJSON js
1523-- | All strings are parsed as expressions
1524instance FromJSON ExpressionOrValue where
1525 parseJSON (String expr) = pure $ Expression expr
1526 parseJSON v = pure $ Value v
1528instance FromJSON Callback where
1529 parseJSON = fmap Callback . parseJSON
1531instance HasSwaggerAesonOptions Server where
1532 swaggerAesonOptions _ = mkSwaggerAesonOptions "server"
1533instance HasSwaggerAesonOptions Components where
1534 swaggerAesonOptions _ = mkSwaggerAesonOptions "components"
1535instance HasSwaggerAesonOptions Header where
1536 swaggerAesonOptions _ = mkSwaggerAesonOptions "header"
1537instance AesonDefaultValue p => HasSwaggerAesonOptions (OAuth2Flow p) where
1538 swaggerAesonOptions _ = mkSwaggerAesonOptions "oauth2" & saoSubObject ?~ "params"
1539instance HasSwaggerAesonOptions OAuth2Flows where
1540 swaggerAesonOptions _ = mkSwaggerAesonOptions "oauth2Flows"
1541instance HasSwaggerAesonOptions Operation where
1542 swaggerAesonOptions _ = mkSwaggerAesonOptions "operation"
1543instance HasSwaggerAesonOptions Param where
1544 swaggerAesonOptions _ = mkSwaggerAesonOptions "param"
1545instance HasSwaggerAesonOptions PathItem where
1546 swaggerAesonOptions _ = mkSwaggerAesonOptions "pathItem"
1547instance HasSwaggerAesonOptions Response where
1548 swaggerAesonOptions _ = mkSwaggerAesonOptions "response"
1549instance HasSwaggerAesonOptions RequestBody where
1550 swaggerAesonOptions _ = mkSwaggerAesonOptions "requestBody"
1551instance HasSwaggerAesonOptions MediaTypeObject where
1552 swaggerAesonOptions _ = mkSwaggerAesonOptions "mediaTypeObject"
1553instance HasSwaggerAesonOptions Responses where
1554 swaggerAesonOptions _ = mkSwaggerAesonOptions "responses" & saoSubObject ?~ "responses"
1555instance HasSwaggerAesonOptions SecurityScheme where
1556 swaggerAesonOptions _ = mkSwaggerAesonOptions "securityScheme" & saoSubObject ?~ "type"
1557instance HasSwaggerAesonOptions Schema where
1558 swaggerAesonOptions _ = mkSwaggerAesonOptions "schema" & saoSubObject ?~ "paramSchema"
1559instance HasSwaggerAesonOptions OpenApi where
1560 swaggerAesonOptions _ = mkSwaggerAesonOptions "swagger" & saoAdditionalPairs .~ [("openapi", "3.0.0")]
1561instance HasSwaggerAesonOptions Example where
1562 swaggerAesonOptions _ = mkSwaggerAesonOptions "example"
1563instance HasSwaggerAesonOptions Encoding where
1564 swaggerAesonOptions _ = mkSwaggerAesonOptions "encoding"
1566instance HasSwaggerAesonOptions Link where
1567 swaggerAesonOptions _ = mkSwaggerAesonOptions "link"
1569instance AesonDefaultValue Server
1570instance AesonDefaultValue Components
1571instance AesonDefaultValue OAuth2ImplicitFlow
1572instance AesonDefaultValue OAuth2PasswordFlow
1573instance AesonDefaultValue OAuth2ClientCredentialsFlow
1574instance AesonDefaultValue OAuth2AuthorizationCodeFlow
1575instance AesonDefaultValue p => AesonDefaultValue (OAuth2Flow p)
1576instance AesonDefaultValue Responses
1577instance AesonDefaultValue SecuritySchemeType
1578instance AesonDefaultValue OpenApiType
1579instance AesonDefaultValue MimeList where defaultValue = Just mempty
1580instance AesonDefaultValue Info
1581instance AesonDefaultValue ParamLocation
1582instance AesonDefaultValue Link
1584instance Arbitrary HttpScheme where
1585 arbitrary = genericArbitrary
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list