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

使用Ajv验证带引用的OpenAPI Schema遇解析错误及整体验证疑问

问题描述
  • 解析OpenAPI Schema文件提取响应Schema片段验证响应体时,若响应Schema引用同一文件内的其他组件Schema,验证会失效,不清楚如何处理这类多引用场景。
  • Ajv无法直接处理完整的OpenAPI Schema对象,报错:Error: strict mode: unknown keyword: "openapi"。想确认:是否可以直接对整个OpenAPI Schema进行验证?若存在大量引用,该如何组合多个Schema?
  • 尝试组合至少两个Schema时,遇到引用解析错误:can't resolve reference testObject.json#/schemas/testObject from id http://example.com/schemas/searchResults.json。

测试文件:test.spec.yaml

schemas:
    testObject:
      $id: http://example.com/schemas/testObject.json
      type: object
      properties:
        prop1:
          type: string
    searchResults:
      $id: http://example.com/schemas/searchResults.json
      type: object
      properties:
        testObjects:
          type: array
          items:
            $ref: "testObject.json#/schemas/testObject"

测试代码

import * as fs from "fs";

import Ajv from "ajv";
import * as yaml from "js-yaml";

describe("test", () => {
  it("should validate the openapi schema", async () => {
    const schema: any = yaml.load(fs.readFileSync("test.spec.yaml", "utf8"));

    const a = schema.schemas.searchResults;
    const b = schema.schemas.testObject;

    const ajv = new Ajv({
      strict: true,
      allErrors: true,
      verbose: false,
      schemas: [a, b],
    });

    const validate: any = ajv.getSchema(
      "http://example.com/schemas/searchResults.json"
    );
    const valid = validate({ testObjects: "foo" });
    if (!valid) throw new Error(JSON.stringify(validate.errors));
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 18:55:08