debian

Debian环境下Swagger API文档如何生成

小樊
34
2025-06-03 08:23:05
栏目: 智能运维

在Debian环境下生成Swagger API文档,通常涉及以下步骤:

  1. 安装Node.js和npm(如果尚未安装):
sudo apt update
sudo apt install -y nodejs npm
  1. 安装Swagger相关依赖
npm install --save @nestjs/swagger swagger-ui-express
  1. 配置Swagger
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';

export const swaggerConfig = new DocumentBuilder()
  .setTitle('你的服务名称')
  .setDescription('你的服务描述')
  .setVersion('1.0')
  .build();

export const createSwaggerDocument = (app: ExpressApplication) => {
  const document = SwaggerModule.createDocument(app, swaggerConfig);
  SwaggerModule.setup('docs', app, document);
};

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  createSwaggerDocument(app);
  await app.listen(3000);
}

bootstrap();
  1. 启动项目

在项目根目录下运行以下命令启动你的Nest.js应用:

npm run start:dev
  1. 访问Swagger UI

启动应用后,打开浏览器并访问 http://localhost:3000/docs,你应该能够看到Swagger UI界面,其中展示了你的API文档。

如果你使用的是Spring Boot项目,步骤类似,但需要使用 springfox 库来配置Swagger。以下是一个简单的Spring Boot配置示例:

添加依赖

pom.xml 中添加以下依赖:

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.9.2</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.9.2</version>
</dependency>

请注意,版本号应根据你的Spring Boot版本进行调整,以避免兼容性问题。

配置Swagger

创建一个配置类来启用Swagger并指定要扫描的包:

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.yourproject")) // 替换为你的Controller包路径
                .paths(PathSelectors.any())
                .build();
    }
}

启动项目并访问Swagger UI

启动你的Spring Boot应用程序后,在浏览器中访问以下URL:

http://localhost:8080/swagger-ui.html

你应该能够看到Swagger生成的API文档界面。

通过以上步骤,你可以在Debian系统上成功生成并访问Swagger API文档。记得根据你的实际API规范调整 swagger.jsonswagger.yaml 文件的内容。

0
看了该问题的人还看了