ubuntu

在Ubuntu上Swagger与其他框架如何协同

小樊
46
2025-03-18 07:17:47
栏目: 编程语言
Ubuntu服务器限时活动,0元免费领! 查看>>

在Ubuntu上,Swagger通常用于API文档生成和测试,它可以与多种框架协同工作,例如Spring Boot、Django、Flask等。以下是一些基本的步骤和示例,展示如何在不同的框架中集成Swagger。

Spring Boot

  1. 添加依赖:在pom.xml文件中添加Swagger的依赖。
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
  1. 配置Swagger:创建一个配置类,使用@EnableSwagger2注解启用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;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}
  1. 访问Swagger UI:启动应用后,访问http://localhost:8080/swagger-ui.html即可查看和测试API文档。

Django

  1. 安装django-rest-framework和drf-yasg
pip install djangorestframework
pip install drf-yasg
  1. 添加应用到settings.py
INSTALLED_APPS = [
    ...
    'rest_framework',
    'drf_yasg',
]

# drf-yasg settings
SWAGGER_SETTINGS = {
    'DEFAULT_INFO': {
        'title': 'My API',
        'version': '1.0',
    },
}
  1. 注册路由:在urls.py中添加Swagger的路由。
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_framework.permissions import IsAuthenticated

schema_view = get_schema_view(
   openapi.Info(
      title="My API",
      default_version='v1',
      description="API documentation",
   ),
   public=True,
   permission_classes=(IsAuthenticated,),
)

urlpatterns = [
    ...
    re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    ...
]
  1. 访问Swagger UI:启动Django应用后,访问http://localhost:8000/swagger/即可查看和测试API文档。

Flask

  1. 安装Flask-RESTful和flask-swagger-ui
pip install Flask-RESTful
pip install flask-swagger-ui
  1. 配置Flask应用
from flask import Flask
from flask_restful import Api
from flask_swagger_ui import get_swaggerui_blueprint

app = Flask(__name__)
api = Api(app)
swaggerui_blueprint = get_swaggerui_blueprint(
   'swagger',
   app.config['SWAGGER_URL'],
   config={
      'app_name': "Flask API"
   }
)
app.register_blueprint(swaggerui_blueprint, url_prefix=app.config['SWAGGER_URL'])

# Add your API endpoints here
  1. 访问Swagger UI:启动Flask应用后,访问http://localhost:5000/swagger/即可查看和测试API文档。

以上示例展示了如何在不同的框架中集成Swagger,以便生成和测试API文档。具体的实现可能会根据框架的版本和配置有所不同,但基本思路是一致的。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:Swagger在Ubuntu上如何测试

0
看了该问题的人还看了