在Ubuntu上,Swagger通常用于API文档生成和测试,它可以与多种框架协同工作,例如Spring Boot、Django、Flask等。以下是一些基本的步骤和示例,展示如何在不同的框架中集成Swagger。
pom.xml
文件中添加Swagger的依赖。<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
@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();
}
}
http://localhost:8080/swagger-ui.html
即可查看和测试API文档。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<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'),
...
]
http://localhost:8000/swagger/
即可查看和测试API文档。pip install Flask-RESTful
pip install flask-swagger-ui
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
http://localhost:5000/swagger/
即可查看和测试API文档。以上示例展示了如何在不同的框架中集成Swagger,以便生成和测试API文档。具体的实现可能会根据框架的版本和配置有所不同,但基本思路是一致的。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:Swagger在Ubuntu上如何测试