Swagger 2 权威指南——第2章 OpenAPI详解(1)

第2章 OpenAPI详解

本章学习目标:

深入理解OpenAPI规范,并能熟练使用OpenAPI规范编写API接口文档

2.1 API服务器和基本URL

在使用OpenAPI规范定义API接口时需要注意,所有的API端点都与基本URL相关。例如,假设基本URL为 http://api.example.com/v1, 那么/users端点指向的就是 http://api.example.com/v1/users

https://api.example.com/v1/users?role=admin&status=active
\________________________/\____/ \______________________/
     server URL          endpoint   query parameters
                         path  

在OpenAPI 3.0中,你可以使用servers数组为API指定多个Base URL。并且每个URL都有一个可选的参数description,description的值可以是markdown或者HTML文本。例如,我们可以定义生产环境和沙箱环境的服务器,如下所示:

servers: 
  - url: https://api.example.com/v1
    description: 生产环境服务器
  - url: https://sandbox-api.example.com:8443/v1
    description: 沙箱环境服务器

2.1.1 服务器URL格式

在OpenAPI规范中,服务器URL遵循RFC 3986标准,通常如下所示:

scheme: //host/[:port][/path]

其中host可以是主机名称或IP地址,OpenAPI 3.0中也支持WebSocket方案 ws://和OpenAPI 2.0中的 wss://。以下是有效的服务器URL示例:

https://api.example.com
https://api.example.com:8443/v1/reports
http://localhost:3025/v1
http://10.0.81.36/v1
ws://api.example.com/v1
wss://api.example.com/v1
/v1/reports
/
//api.example.com

如果服务器URL是相对路径,那么会针对托管给定OpenAPI定义文件的服务器进行解析(详见2.1.4节)。注意: 服务器URL不得包含查询字符串参数,如下所示是无效的:

https://api.example.com/v1?route=

如果servers参数值为null,则默认服务器URL为: /

2.1.2 服务器模板

服务器URL的任何部分都可以使用变量进行参数化,变量由服务器URL中的{花括号}表示,如下所示:

servers:
  - url: https://{customerId}.saas-app.com:{port}/v2
    variables:
      customerId:
        default: demo
        description: Customer ID assigned by the service provider
      port:
        enum:
          - '443'
          - '8443'
        default: '443'

与路径参数不同,服务器变量不使用schema,如果使用则会被认为是普通字符串。变量可以具有任意值,也可以限制为enum。在任何情况下,default都需要一个值,如果客户端不提供值,将使用该值。变量description是可选的。服务器模板的常见用例:

  • 指定多个协议(例如HTTP或HTTPS)
  • SaaS(托管)应用程序,其中每个客户都有自己的子域。
  • 不同地理区域服务器(例如:Amazon Web Services)。
  • SaaS和内部部署API的单一API定义。

指定HTTPS和HTTP

servers: 
  - url: http://api.example.com
  - url: https://api.example.com

或使用模板

servers: 
  - url: '{protocol}://api.example.com'
    variables: 
      protocol: 
        enum: 
          - http
          - https
        default: https

注意: 这两个示例在语义上是不同的,第二个示例显示设置默认服务器是HTTPS,而第一个示例没有默认服务器。

指定多环境

可以使用模板分别指定生产、开发等服务器,如下所示:

servers: 
  - url: https://{envrionment}.example.com/v2
    variables: 
      environment: 
        default: api
        enum: 
          - api
          - api.dev
          - api.staging

SaaS和内部部署

servers:
  - url: '{server}/v1'
    variables:
      server:
        default: https://api.example.com  # SaaS server

不同地理区域的区域端点

servers:
  - url: https://{region}.api.cognitive.microsoft.com
    variables:
      region:
        default: westus
        enum:
          - westus
          - eastus2
          - westcentralus
          - westeurope
          - southeastasia

2.1.3 覆盖服务器

servers可以在路径级别或操作级别上覆盖全局数组,如果某些端点使用与API其余部分不同的服务器或基本路径,则很容易实现。常见的例子是:

  • 用于文件上传和下载的操作的不同基本URL。
  • 已经弃用但是仍具有功能的端点。
servers:
  - url: https://api.example.com/v1
paths:
  /files:
    description: File upload and download operations
    servers:
      - url: https://files.example.com
        description: Override base path for all operations with the /files path
    ...
  /ping:
    get:
      servers:
        - url: https://echo.example.com
          description: Override base path for the GET /ping operation

2.1.4 相对URL

servers数组中的URL可以是相对的,例如/v2,在这种情况下,将针对承载给定OpenAPI定义的服务器解析URL。这在客户自己的服务器上托管的本地安装中很有用。例如,如果托管的定义为 http://localhost:3001/openapi.yaml 指定 url: /v2,url则解析为 http://localhost:3001/v2 。相对URL解析规则遵循RFC 3986。此外,API定义中几乎所有其他URL(包括OAuth流端点),termsOfService,外部文档URL或者其他,都可以相对于服务器URL进行指定。如下所示:

servers:
  - url: https://api.example.com
  - url: https://sandbox-api.example.com
# Relative URL to Terms of Service
info:
  version: 0.0.0
  title: test
  termsOfService: /terms-of-use
# Relative URL to external documentation
externalDocs:
  url: /docs
  description: Find more info here
# Relative URLs to OAuth2 authorization and token URLs
components:
  securitySchemes:
    oauth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: /oauth/dialog
          tokenUrl: /oauth/token
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将Struts 1整合Swagger 2,您需要完成以下步骤: 1. 添加Swagger依赖项:您需要将Swagger的Maven依赖项添加到您的项目中,以便在项目中使用Swagger的注解和API。 2. 配置Swagger:您需要在项目中配置Swagger,以便在API中使用Swagger注解。您可以使用Swagger配置类来配置Swagger属性,例如API文档的标题和版本等。 3. 配置Struts 1拦截器:您需要将Swagger拦截器添加到Struts 1拦截器链中,以便在运行时生成API文档。您需要将Swagger拦截器添加到ActionServlet的配置文件中。 4. 编写Swagger注解:您需要在您的控制器方法中使用Swagger注解来定义API操作,例如操作名称,HTTP方法,参数和响应等。 5. 运行项目:当您运行项目时,Swagger将自动生成API文档,您可以通过Swagger UI查看和测试API。 下面是一个简单的示例: 1. 添加Swagger Maven依赖项: ```xml <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.22</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.5.22</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-core</artifactId> <version>1.5.22</version> </dependency> ``` 2. 配置Swagger: ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("My API") .description("API documentation for my application") .version("1.0") .build(); } } ``` 3. 配置Struts 1拦截器: ```xml <action-mappings> ... </action-mappings> <plug-in className="io.swagger.jaxrs.listing.SwaggerSerializers" /> <plug-in className="io.swagger.jaxrs.listing.ApiListingResource" > <set-property propertyName="swagger.api.basepath" value="/myapp/api" /> </plug-in> ``` 4. 编写Swagger注解: ```java @Api(value = "users", description = "Operations related to users") @RestController @RequestMapping("/users") public class UserController { @ApiOperation(value = "Get all users", response = List.class) @GetMapping public List<User> getUsers() { ... } @ApiOperation(value = "Create a new user", response = User.class) @PostMapping public User createUser(@RequestBody User user) { ... } @ApiOperation(value = "Update an existing user", response = User.class) @PutMapping("/{id}") public User updateUser(@PathVariable("id") Long id, @RequestBody User user) { ... } @ApiOperation(value = "Delete a user") @DeleteMapping("/{id}") public void deleteUser(@PathVariable("id") Long id) { ... } } ``` 5. 运行项目: 在运行项目后,您可以通过访问Swagger UI来查看和测试API: http://localhost:8080/myapp/api/swagger-ui.html

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值