-
-
Notifications
You must be signed in to change notification settings - Fork 2
Configuring Swagger
Swagger is a powerful tool for documenting and testing APIs. In NestJS, you can easily integrate Swagger using the @nestjs/swagger package and swagger-ui-express. Below, I’ll explain how to set up Swagger in your NestJS application and configure it to work seamlessly with your Crudify-generated APIs.
First, install the necessary packages using npm or yarn:
npm install @nestjs/swagger swagger-ui-expressIn your main.ts file, configure Swagger using the DocumentBuilder and SwaggerModule. This setup allows you to customize the Swagger documentation to fit your application's needs.
Here’s an example configuration:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Swagger configuration
const config = new DocumentBuilder()
.setTitle('Crudify API') // Set the title of the API
.setDescription('API generated by Crudify') // Set the description
.setVersion('1.0') // Set the API version
.build();
// Create the Swagger document
const document = SwaggerModule.createDocument(app, config);
// Set up the Swagger UI endpoint
SwaggerModule.setup('api', app, document, {
swaggerOptions: {
filter: true, // Enable filtering by tag
},
});
await app.listen(3000);
}
bootstrap();To organize your API endpoints in Swagger, you can use the @ApiTags decorator from the @nestjs/swagger package. This decorator allows you to group related endpoints under a specific tag, making it easier for users to navigate and understand your API documentation.
In your controller, use the @ApiTags decorator to specify a tag for all endpoints within that controller. For example, if you have a UserController, you can group all user-related endpoints under the users tag.
Here’s an example:
import { Controller } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { UserService } from './user.service';
import { User } from './user.entity';
import { Crudify, CrudifyController } from 'ncrudify';
@ApiTags('users') // Group all endpoints under the 'users' tag
@Crudify({
model: {
type: User, // Define your Mongoose model
},
})
@Controller('users')
export class UserController extends CrudifyController<User> {
constructor(public service: UserService) {
super(service);
}
}The @ApiTags decorator provides the following benefits:
- Improved Organization: Endpoints are grouped logically, making it easier for users to find related operations.
- Better Readability: Tags act as categories in the Swagger UI, improving the overall readability of your API documentation.
-
Filtering: If you enabled the
filter: trueoption in the Swagger UI configuration, users can filter endpoints by tags for a more focused view.
Once you’ve added @ApiTags to your controllers, the Swagger UI will display your endpoints grouped by their respective tags. For example:
-
users: Contains all user-related endpoints (e.g.,GET /users,POST /users). -
products: Contains all product-related endpoints (e.g.,GET /products,POST /products).
This grouping makes it easier for users to navigate and test your API.
The DocumentBuilder is used to define the metadata for your Swagger documentation. It includes:
-
.setTitle('Crudify API'): Sets the title of your API. -
.setDescription('API generated by Crudify'): Provides a description of your API. -
.setVersion('1.0'): Specifies the version of your API.
You can also add additional configurations, such as:
-
.addTag('users'): Adds tags to group related endpoints. -
.addBearerAuth(): Adds authentication support for your API.
This method generates the Swagger document based on the configuration and your application’s routes.
This method sets up the Swagger UI at the /api endpoint. The swaggerOptions object allows you to customize the Swagger UI behavior:
-
filter: true: Enables filtering by tag, making it easier for users to navigate your API documentation.
This setup was designed to provide users with the maximum configurability for their Swagger documentation. Here’s why:
-
Customizable Metadata: The
DocumentBuilderallows you to define the title, description, version, and tags for your API, making it easy to tailor the documentation to your application. -
Flexible Swagger UI Options: The
swaggerOptionsparameter inSwaggerModule.setuplets you customize the Swagger UI behavior, such as enabling filtering or adding custom styles. -
Integration with
Crudify: By configuring Swagger inmain.ts, you ensure that all routes, including those generated byCrudify, are automatically documented without additional effort. -
Clear Separation of Concerns: Keeping the Swagger configuration in
main.tsensures that your application’s bootstrap logic remains clean and focused.
To further enhance your Swagger documentation, you can add tags and authentication support.
const config = new DocumentBuilder()
.setTitle('Crudify API')
.setDescription('API generated by Crudify')
.setVersion('1.0')
.addTag('users', 'Operations related to users') // Add a tag for user-related endpoints
.addTag('products', 'Operations related to products') // Add a tag for product-related endpoints
.build();const config = new DocumentBuilder()
.setTitle('Crudify API')
.setDescription('API generated by Crudify')
.setVersion('1.0')
.addBearerAuth() // Add Bearer token authentication support
.build();Once your application is running, you can access the Swagger UI by navigating to:
http://127.0.0.1:3000/api
Here, you’ll see all your API endpoints, grouped by tags (if configured), and you can test them directly from the browser.
-
Install
@nestjs/swaggerandswagger-ui-express: These packages are required to integrate Swagger into your NestJS application. -
Configure Swagger in
main.ts: Use theDocumentBuilderandSwaggerModuleto set up Swagger documentation. -
Customize Swagger UI: Use
swaggerOptionsto enable filtering or other UI customizations. -
Maximize Configurability: This setup ensures that your Swagger documentation is flexible and integrates seamlessly with
Crudify.
By following this guide, you can easily configure Swagger for your NestJS application and provide a user-friendly API documentation experience. Let me know if you need further assistance! 🚀