阅读量:2
在Ubuntu上,Swagger通常用于API文档生成和测试,它可以与多种框架协同工作,例如Spring Boot、Django、Flask等。以下是一些基本的步骤和示例,展示如何在不同的框架中集成Swagger。
Spring Boot
- 添加依赖:在
pom.xml文件中添加Swagger的依赖。
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-boot-starterartifactId>
<version>3.0.0version>
dependency>
- 配置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();
}
}
- 访问Swagger UI:启动应用后,访问
http://localhost:8080/swagger-ui.html即可查看和测试API文档。
Django
- 安装django-rest-framework和drf-yasg:
pip install djangorestframework
pip install drf-yasg
- 添加应用到
settings.py:
INSTALLED_APPS = [
...
'rest_framework',
'drf_yasg',
]
# drf-yasg settings
SWAGGER_SETTINGS = {
'DEFAULT_INFO': {
'title': 'My API',
'version': '1.0',
},
}
- 注册路由:在
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\.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'),
...
]
- 访问Swagger UI:启动Django应用后,访问
http://localhost:8000/swagger/即可查看和测试API文档。
Flask
- 安装Flask-RESTful和flask-swagger-ui:
pip install Flask-RESTful
pip install flask-swagger-ui
- 配置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
- 访问Swagger UI:启动Flask应用后,访问
http://localhost:5000/swagger/即可查看和测试API文档。
以上示例展示了如何在不同的框架中集成Swagger,以便生成和测试API文档。具体的实现可能会根据框架的版本和配置有所不同,但基本思路是一致的。
以上就是关于“在Ubuntu上Swagger与其他框架如何协同”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm