Ehs*_*ari 7 javascript swagger next.js
有没有办法为 NEXT.js API 路由提供一个 swagger 文档?我正在使用 Next.js 进行前端和后端开发,并且我想为我使用 Next.js 开发的 API 提供一个 swagger 文档。
您可以使用以下项目来引导 Next.js 和 Swagger 之间的集成
yarn add next-swagger-doc swagger-ui-react
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
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',
});
};
Run Code Online (Sandbox Code Playgroud)
您必须拥有 APIS 的 swagger json 文件或规范,并且可以使用Swagger UI或Redoc等库
使用 Redoc,您可以执行 /doc/[slug].js 并对文档(或 swagger ui)的 .json 或 yaml 文件进行动态获取
这个网站: https: //openapi.tools/,有很多用于React和OpenAPI的工具,你可以使用它。
| 归档时间: |
|
| 查看次数: |
937 次 |
| 最近记录: |