【问题标题】:Case Insensitive String parameter in schema of openApiopenApi架构中不区分大小写的字符串参数
【发布时间】:2020-03-20 10:55:40
【问题描述】:

我有一个开放的 API 规范,其参数如下:

- name: platform
  in: query
  description: "Platform of the application"
  required: true
  schema:
    type: string
    enum:
      - "desktop"
      - "online"

当我从 URL 获取“平台”参数时,它可以是这样的:

platform=online or 
platform=ONLINE or 
platform=Online or 
platform=onLine  or ... any other format

但是当我要使用它时,它只有在参数像“platform=online”一样都是小写的情况下才有效,显然是为了匹配枚举值。

如何使架构不区分大小写并理解所有类型的传递参数?

【问题讨论】:

    标签: enums openapi


    【解决方案1】:

    枚举区分大小写。要使用不区分大小写的架构,您可以改用正则表达式 pattern

    - name: platform
      in: query
      description: 'Platform of the application. Possible values: `desktop` or `online` (case-insensitive)'
      required: true
      schema:
        type: string
        pattern: '^[Dd][Ee][Ss][Kk][Tt][Oo][Pp]|[Oo][Nn][Ll][Ii][Nn][Ee]$'
    

    请注意,pattern 是模式本身,不支持 JavaScript 正则表达式文字语法 (/abc/i),这意味着您不能像 i 一样指定 flags(不区分大小写的搜索)。因此,您需要在模式本身中同时指定大写和小写字母。


    或者,在description而不是pattern/enum中指定可能的值,并在后端验证参数值。

    【讨论】:

    • 谢谢,但有没有保留枚举?并且不要对我的代码进行进一步的更改?我可以为枚举值提供这种模式匹配吗?
    • 仅当您扩展枚举以包含所有可能的拼写时:enum: [online, ONLINE, Online, OnLiNe, ...]。真的没有优雅的方式来描述这种情况。
    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 2022-11-22
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 2010-09-05
    相关资源
    最近更新 更多