繁体   English   中英

Next.js 与 Swagger

[英]Next.js with Swagger

有没有办法为 NEXT.js API 路由提供 swagger 文档? 我将 Next.js 用于前端和后端开发,并且我希望为我使用 Next.js 开发的 API 提供一个 swagger 文档。

您必须拥有 swagger json 文件或 APIS 规范,并且可以使用诸如Swagger UIRedoc 之类的库

使用 Redoc,您可以执行 /doc/[slug].js 并动态获取 .json 或 yaml 文件(或 swagger ui)

这个网站: https://openapi.tools/ ,有很多通用的 React 和 OpenAPI 工具,你可以使用它。

您可以使用以下项目来引导 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',
  });
};

我制作了一个小 npm 库,它可以从您的 NextJS 项目中自动生成 Swagger 文档。 无需用户输入!

仍然非常Beta,但希望它有用。 https://www.npmjs.com/package/nextjs-routes-docs

赶紧跑

npx nextjs-routes-docs [dir]

从 API 路由自动生成 OpenAPI 规范文件的另一种解决方案是使用 Next REST Framework: https ://github.com/blomqma/next-rest-framework

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM