有没有办法为 NEXT.js API 路由提供一个 Swagger 的文档?
我正在使用 Next.js 进行前端和后端开发,并且我希望为我使用 Next.js 开发的 API 提供一个 Swagger 的文档。
最佳答案
您可以使用以下项目来引导 Next.js 和 Swagger 之间的集成
yarn add next-swagger-doc swagger-ui-react
import { GetStaticProps, InferGetStaticPropsType } from 'next';
import { createSwaggerSpec } from 'next-swagger-doc';
import SwaggerUI from 'swagger-ui-react';
import 'swagger-ui-react/swagger-ui.css';
const ApiDoc = ({ spec }: InferGetStaticPropsType<typeof getStaticProps>) => {
return <SwaggerUI spec={spec} />;
};
export const getStaticProps: GetStaticProps = async ctx => {
const spec: Record<string, any> = createSwaggerSpec({
title: 'NextJS Swagger',
version: '0.1.0',
});
return { props: { spec } };
};
export default ApiDoc;
Next.js API 路由端点的实际定义如下所示:/**
* @swagger
* /api/hello:
* get:
* description: Returns the hello world
* responses:
* 200:
* description: hello world
*/
const handler = (_req: NextApiRequest, res: NextApiResponse) => {
res.status(200).json({
result: 'hello world',
});
};
关于javascript - Next.js 与 Swagger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66955625/