swaggernestjsnestjs-swagger

Add Swagger base path field in Nest.js project


I am trying to use nestjs/swagger to create a swagger file from my back-end and I am facing a problem related to the base path. What I want to achieve is to show version as base path instead of showing it in all the methods available, which is ugly and confusing.

My API, right now, has the following structure (this is a set of what is present in app.module.ts):

const routes: Routes = [
  {
    path: '/api',
    module: ApiModule,
    children: [
      {
        path: '/v1',
        module: V1Module,
        children: [
          {
            path: '/orders',
            module: OrdersModule
          },
          {
            path: '/users',
            module: UsersModule
          }
        ]
      }
    ]
  }
];

This way, once I generate and check the swagger, I see all my methods following the /api/v1 prefix. This could be an example:

orders

GET   /api/v1/orders
POST  /api/v1/orders
GET   /api/v1/orders/{order_id}
...

users

GET   /api/v1/users
POST  /api/v1/users
GET   /api/v1/users/{user_id}
...

What I want is to get rid of /api/v1 appearing in any method. I know that SWAGGER has fields for host and basePath, but do not find any way to populate it in Nest.js. Researching, I have found that there were .setBasePath() and .addServer() methods, but they do not work for me (I am pretty sure they are deprecated).

Thank very much for your help.


Solution

  • If you want nestjs to add api/v1 to every endpoint then use setGlobalPrefix('api/v1') to do that.

    https://docs.nestjs.com/faq/global-prefix#global-prefix