JSON Schema 校验,其实就是 对接口返回的数据结构做自动化校验,确保它符合预期格式。
比如下单接口返回的数据是这样的:
{
"orderId": 12345,
"status": "paid",
"amount": 58.5,
"items": [
{
"productId": 1001,
"name": "苹果",
"quantity": 2
}
]
}
我们用 JSON Schema 定义接口的“标准格式”,比如:
{
"type": "object",
"properties": {
"orderId": { "type": "integer" },
"status": { "type": "string" },
"amount": { "type": "number" },
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"productId": { "type": "integer" },
"name": { "type": "string" },
"quantity": { "type": "integer" }
},
"required": ["productId", "name", "quantity"]
}
}
},
"required": ["orderId", "status", "amount", "items"]
}
然后用工具(比如 Python 的 jsonschema 库)去校验:
orderId 必须是整数
status 必须是字符串
items 必须是数组,数组里的元素必须包含 productId、name、quantity
作用:
保证接口返回格式正确:字段名、类型、是否必填。
防止上线后出错:比如后端改了字段类型,前端/测试能第一时间发现。
配合自动化:写一次 Schema,就能自动化校验所有返回。
面试回答模板
如果面试官问 “JSON Schema 校验你怎么用的?”
你可以这样说:
👉 “我们在接口测试里引入了 JSON Schema 校验,比如订单接口返回的字段结构,我会用 jsonschema 库定义标准,然后在自动化测试里比对接口实际返回和 Schema 是否一致。这样可以快速发现字段缺失、类型不符的问题,保证接口返回的稳定性。”
代码举例:写一段 Python 示例代码,用 jsonschema 来校验接口返回。
示例代码:校验订单接口返回
import requests
from jsonschema import validate
-
定义接口返回的 JSON Schema
order_schema = {
"type": "object",
"properties": {
"orderId": {"type": "integer"},
"status": {"type": "string"},
"amount": {"type": "number"},
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"productId": {"type": "integer"},
"name": {"type": "string"},
"quantity": {"type": "integer"}
},
"required": ["productId", "name", "quantity"]
}
}
},
"required": ["orderId", "status", "amount", "items"]
} -
调用接口(示例 URL)
url = "http://api.demo.com/order/detail?orderId=12345"
response = requests.get(url)
data = response.json() -
用 Schema 校验返回结果
try:
validate(instance=data, schema=order_schema)
print("✅ 接口返回符合预期 Schema")
except Exception as e:
print("❌ 接口返回不符合 Schema:", e)
在面试时还可以说:
“我会在接口自动化里加 Schema 校验,保证返回结构和字段类型稳定。”
“比如订单接口返回的 orderId 必须是整型,items 必须是数组,如果后端改了类型,测试用例能第一时间发现。”
“这比单纯的断言字段值更健壮,能防止上线后出现前端解析报错。”
这样在面试时你就可以加一句:
👉 “除了常规的断言,我还会用 jsonschema 库做接口返回的 Schema 校验,保证接口结构稳定。”