Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastify addSchema to provide meaningful name of the OpenAPI 2.0 definition objects

I have some schema definitions created with fastify as in below, where I have used 'title' to give meaningful name of my models.

fastify.addSchema({
        $id: 'persistence-query-params',
        title: "PersistenceQueryParams",   // Here
        type: 'object',
        description: 'Persistence Service GET API URL query specification. Applicable for GET API only.',
        properties: {
               ...........
        },
    });

However when I am looking at the json generated from the swagger (I am using fastify-swagger: 4.8.4 and fastify: 3.20.1), I am seeing this

  def-7:                    ## Here
    title: PersistenceQueryParams
    type: object
    description: >-
      Persistence Service GET API URL query specification. Applicable for GET
      API only.
    properties:

This is coming up in the OpenAPI 2.0 https://editor.swagger.io/, when loading the json generated out of that schema.

I have tried out adding the name field also:

name: "PersistenceQueryParams",

However no luck.

How can I create meaningful names, instead of def-0, def-1 etc in OpenAPI 2.0?

Thanks, Pradip

like image 902
Pradip Avatar asked Sep 20 '25 11:09

Pradip


1 Answers

For anyone reading this now it is now possible to do this. You need to override the refResolver in the config like this:

fastify.register(swagger, {
    refResolver: {
      buildLocalReference(json, baseUri, fragment, i) {
        // This mirrors the default behaviour
        // see: https://github.com/fastify/fastify-swagger/blob/1b53e376b4b752481643cf5a5655c284684383c3/lib/mode/dynamic.js#L17
        if (!json.title && json.$id) {
          json.title = json.$id;
        }
        // Fallback if no $id is present
        if (!json.$id) {
          return `def-${i}`;
        }

        return `${json.$id}`;
      },
    },
    openapi: {
      // Your spec here...
    }
  });

Clickable comment link:

https://github.com/fastify/fastify-swagger/blob/1b53e376b4b752481643cf5a5655c284684383c3/lib/mode/dynamic.js#L17

Now you're refs will have meaningful names.

like image 186
Nico Krätschmer Avatar answered Sep 23 '25 09:09

Nico Krätschmer