You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Prism(NPM)Mock API时路径参数messageid不生效问题

解决Prism Mock不同路径参数返回相同响应的问题

问题原因

Prism 默认不会自动根据路径参数匹配对应的响应示例,除非你明确为每个示例配置匹配规则。如果只是在OpenAPI文档里简单罗列多个示例,Prism要么返回第一个示例,要么随机返回,不会根据messageid参数值区分。

解决步骤

1. 修正OpenAPI文档的示例定义

在每个响应示例中添加x-prism-matches扩展字段,指定该示例匹配的messageid参数值。以下是符合要求的OpenAPI 3.0.2示例片段:

openapi: 3.0.2
info:
  title: Message API
  version: 1.0.0
paths:
  /message/{messageid}:
    get:
      parameters:
        - name: messageid
          in: path
          required: true
          schema:
            type: string # 注意参数类型要和匹配值一致,如果是数字就写type: integer
      responses:
        '200':
          description: 成功返回消息
          content:
            text/plain:
              examples:
                msg1:
                  summary: messageid=1时的响应
                  value: "Hello from 1, World!"
                  x-prism-matches:
                    parameters:
                      messageid: "1" # 和参数类型一致,字符串加引号,数字则直接写1
                msg2:
                  summary: messageid=2时的响应
                  value: "Goodbye from 2, World!"
                  x-prism-matches:
                    parameters:
                      messageid: "2"

2. 升级Prism到最新版本

旧版本Prism可能不支持x-prism-matches扩展,执行以下命令升级:

npm install -g @stoplight/prism-cli

3. 启用动态Mock模式启动服务

启动Mock服务时加上--mock=dynamic参数,确保Prism启用基于请求参数匹配示例的逻辑:

prism mock --mock=dynamic ".\SwaggerSignIn\sample.yml"

验证

重新启动服务后,请求http://127.0.0.1:4010/message/1应该返回"Hello from 1, World!",请求http://127.0.0.1:4010/message/2返回"Goodbye from 2, World!"。

常见坑点

  • 参数类型不匹配:如果messageid的schema定义是integer,那么x-prism-matches里的参数值要写1而不是"1",否则匹配失败。
  • 示例未配置x-prism-matches:Prism会默认返回第一个示例或者随机返回,不会根据参数区分。

内容的提问来源于stack exchange,提问作者balvinder dhillon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 20:52:10