biocad / servant-openapi3

OpenAPI 3.0 for Servant
BSD 3-Clause "New" or "Revised" License
38 stars 23 forks source link

Type schemas in query params are inlined, rather than referenced #37

Open georgefst opened 1 year ago

georgefst commented 1 year ago

Is there any particular reason for this behaviour? It is inconsistent with what happens for request bodies, as shown below.

This can make types used in query parameters difficult for clients to work with, since they can't easily be referenced by name, and a type used in different endpoints may generate multiple equivalent type definitions.

(I have looked a little at trying to implement this myself. My approach was to try to make the HasOpenApi (QueryParam' mods sym a :> sub) instance in src/Servant/OpenApi/Internal.hs more like the HasOpenApi (ReqBody' mods cs a :> sub) instance. I got stuck upon realising that declareSchemaRef works with ToSchema, but we only have ToParamSchema. I don't know enough about this library or openapi3 to know what should be done next, or whether there's some fundamental limitation.)

main = do
    T.writeFile "body.json" $
        decodeUtf8 . BL.toStrict . encodePretty . toOpenApi $
            Proxy @(ReqBody '[JSON] Level :> GetNoContent)
    T.writeFile "param.json" $
        decodeUtf8 . BL.toStrict . encodePretty . toOpenApi $
            Proxy @(QueryParam "query" Level :> GetNoContent)

data Level = Beginner | Intermediate | Expert deriving (Generic, ToParamSchema, ToSchema)

body.json

{
  "components": {
    "schemas": {
      "Level": {
        "enum": ["Beginner", "Intermediate", "Expert"],
        "type": "string"
      }
    }
  },
  "info": {
    "title": "",
    "version": ""
  },
  "openapi": "3.0.0",
  "paths": {
    "/": {
      "get": {
        "requestBody": {
          "content": {
            "application/json;charset=utf-8": {
              "schema": {
                "$ref": "#/components/schemas/Level"
              }
            }
          }
        },
        "responses": {
          "204": {
            "description": ""
          },
          "400": {
            "description": "Invalid `body`"
          }
        }
      }
    }
  }
}

param.json

{
  "components": {},
  "info": {
    "title": "",
    "version": ""
  },
  "openapi": "3.0.0",
  "paths": {
    "/": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "query",
            "required": false,
            "schema": {
              "enum": ["Beginner", "Intermediate", "Expert"],
              "type": "string"
            }
          }
        ],
        "responses": {
          "204": {
            "description": ""
          },
          "400": {
            "description": "Invalid `query`"
          }
        }
      }
    }
  }
}