溫馨提示×

在Ubuntu上Swagger與其他框架如何協同

小樊
46
2025-03-18 07:17:47
欄目: 編程語言

在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文檔。具體的實現可能會根據框架的版本和配置有所不同,但基本思路是一致的。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女