fastify / fastify-swagger

Swagger documentation generator for Fastify
MIT License
889 stars 199 forks source link

Custom "examples" names and summaries for request body, params, etc #770

Closed mouhannad-sh closed 7 months ago

mouhannad-sh commented 7 months ago

Prerequisites

🚀 Feature Proposal

Support distinct examples name for request body, params, etc..

Motivation

The openapi v3 spec supports adding a distinct name and summary for each example as shown here https://swagger.io/docs/specification/adding-examples/

parameters:
  - in: query
    name: limit
    schema:
      type: integer
      maximum: 50
    examples:       # Multiple examples
      zero:         # Distinct name
        value: 0    # Example value
        summary: A sample limit value  # Optional description
      max: # Distinct name
        value: 50   # Example value
        summary: A sample limit value  # Optional description
image

unfortunately, it seems like an object format which is not allowed in the current implementation due to the dependency on fast-json-stringify and it's schema validator

https://github.com/fastify/fast-json-stringify/blob/4f6f7b809fc7148a40e8f07cc81a658757e81b68/lib/schema-validator.js#L203C1-L206C2

There's probably a good reason for that. but I'm wondering if there's a way around it?

I'm happy to contribute once I have a decent understanding on what can be done

Example

The current convertor implementation in this library forces examples to be named as example 1, example 2, ...

https://github.com/fastify/fastify-swagger/blob/5277980820f96a7831d026dbc280f2d3a2972f4f/lib/spec/openapi/utils.js#L148-L158

Eomm commented 7 months ago

Thanks for reporting! Would you like to send a Pull Request to address this issue? Remember to add unit tests.

jiroler commented 7 months ago

I faced to the same problem and found this solution: https://github.com/fastify/fastify-swagger#add-examples-to-the-schema

mouhannad-sh commented 7 months ago

thanks @jiroler I'll test it out and report back. if that doesn't work then I might submit a PR !

mouhannad-sh commented 7 months ago

I can confirm that it works ! in my case I'm using it with Typebox

fastify({
    ajv: {
      plugins: [
        function (ajv) {
          ajv.addKeyword({ keyword: 'x-examples' })
        }
      ]
    }
  })

// hypothetical schema 
Type.Object(Type.Any(), {
  "x-examples": {
    Cats: {
      summary: "Feed cats",
      description:
        "A longer **description** of the options with cats",
      value: {
        animals: ["Tom", "Garfield", "Felix"]
      }
    },
    Dogs: {
      summary: "Feed dogs",
      value: {
        animals: ["Spike", "Odie", "Snoopy"]
      }
    }
  }
});