简体   繁体   English

使用Swagger 2.0进行REST API版本控制

[英]REST API Versioning with Swagger 2.0

I needed my Node REST API's to be versioned. 我需要对我的Node REST API进行版本控制。 I am using swagger 2.0 for the validation middleware and documentation. 我使用swagger 2.0作为验证中间件和文档。 Currently i have only a single swagger yml file that is used for all purposed. 目前我只有一个swagger yml文件,用于所有目的。

I am using url prefixes (version number: /v1/... /v2/... etc) to support versioning in my Node Rest API. 我正在使用url前缀(版本号:/ v1 / ... / v2 / ...等)来支持我的Node Rest API中的版本控制。 And i need to support multiple versions at any point of time. 我需要在任何时候支持多个版本。

  1. Should i create a separate swagger yml file for each API version? 我应该为每个API版本创建一个单独的swagger yml文件吗? If yes, how to load/manage multiple swagger yml files in the swagger-validation middleware 如果是,如何在swagger验证中间件中加载/管理多个swagger yml文件
  2. Does Swagger 2.0 format specification allow definition of versioned paths within the same file. Swagger 2.0格式规范是否允许在同一文件中定义版本化路径。

Swagger does not specify a versioning scheme simply because there is no single solution, and forcing one approach to use the spec would not make sense. Swagger没有简单地指定版本控制方案,因为没有单一的解决方案,强制一种方法使用规范是没有意义的。 Here are common techniques that I've seen: 以下是我见过的常用技巧:

1) Tie your authentication to a version. 1)将您的身份验证绑定到版本。 I think this is the coolest way to handle versioning but is also the most expensive to support and maintain. 我认为这是处理版本控制的最酷方式,但也是支持和维护最昂贵的方法。 Based on, for example the api key being used to access your service, you can keep track of the version that they're expecting to access, and route it to the right server. 例如,基于用于访问服务的api密钥,您可以跟踪他们期望访问的版本,并将其路由到正确的服务器。 In this case, you can simply have multiple services running, with different swagger definitions. 在这种情况下,您可以简单地运行多个服务,并使用不同的swagger定义。

2) Use a path part to indicate the version. 2)使用路径部分指示版本。 That means you have a /v2 or /v3 in your path, and based on that, some routing logic points you to the right server. 这意味着您的路径中有/v2/v3 ,并且基于此,某些路由逻辑将您指向正确的服务器。 Again, a separate swagger definition. 再一次,一个单独的招摇定义。

3) Based on some header, let the user choose what server to talk to. 3)基于某些标题,让用户选择要与之通话的服务器。 This is pretty unintuitive, but it can work. 这非常不直观,但它可以工作。 You should always have a default version (typically the latest) 你应该总是有一个默认版本(通常是最新版本)

That said, all of the above solutions mean multiple swagger files. 也就是说,上述所有解决方案都意味着多个招摇文件。 You can use the $ref syntax to link and reuse portions of the spec. 您可以使用$ ref语法来链接和重用规范的各个部分。

I believe with swagger-tools, you can have multiple instances listening for requests. 我相信使用swagger工具,您可以让多个实例监听请求。 You just need a routing tier in front of them to handle the different versioning that you choose. 您只需要在它们前面有一个路由层来处理您选择的不同版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM