Hướng dẫn cấu hình Swagger trong NextJS
1. Mục tiêu
2. Cài đặt các thư viện cần thiết
npm install swagger-jsdoc swagger-ui-dist
npm install @types/swagger-jsdoc @types/swagger-ui-dist --save-dev3. Tạo API Route để trả về Swagger JSON
Tạo file pages/api/swagger.ts:
import { NextApiRequest, NextApiResponse } from 'next';
import swaggerJSDoc from 'swagger-jsdoc';
const swaggerDefinition = {
openapi: '3.0.0',
info: {
title: 'My API',
version: '1.0.0',
description: 'API documentation for My App',
},
servers: [
{ url: 'http://localhost:3000' },
],
};
const options = {
swaggerDefinition,
apis: ['./pages/api/**/*.ts'],
};
const swaggerSpec = swaggerJSDoc(options);
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'GET') {
res.status(200).json(swaggerSpec);
} else {
res.status(405).json({ message: 'Method Not Allowed' });
}
}4. Tạo trang Swagger UI để hiển thị tài liệu API
Tạo file pages/swagger.tsx:
5. Tắt Layout cho trang Swagger
6. Thêm các Comment JSDoc vào API Route
7. Truy cập Swagger UI
8. Tóm tắt
Last updated