跳到主要内容

oas-validator

oas-validation 插件允许根据符合 Open API v3 规范的 API 定义来验证 HTTP 请求和响应。

示例

以下示例将使用 Swagger Petstore Open API 规范

export OPEN_API_SPEC=$(curl -s "https://petstore3.swagger.io/api/v3/openapi.json" | sed 's/"/\\"/g')

验证请求体

此示例演示了如何根据给定规范验证请求体。

创建一个使用 OAS validator 插件的路由:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "body_validation",
"uri": "/*",
"plugins": {
"oas-validator": {
"spec": "'"${OPEN_API_SPEC}"'"
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"petstore3.swagger.io:443": 1
},
"scheme": "https",
"pass_host": "node"
}
}'

验证失败

使用不满足定义的 Open API 规范的请求体向上述路由发送请求:

curl -i "http://127.0.0.1:9080/api/v3/pet" -X POST \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{"invalid-body": "this is an invalid body"}'

你应该会看到 HTTP/1.1 400 Bad Request 响应,其响应体类似于以下内容:

{"message":"failed to validate request."}

验证成功

使用有效的请求体向路由发送请求:

curl -i "http://127.0.0.1:9080/api/v3/pet" -X POST \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"id": 1,
"name": "doggie",
"category": { "id": 1, "name": "Dogs" },
"photoUrls": ["string"],
"tags": [{ "id": 1, "name": "tag1" }],
"status": "available"
}'

你应该会看到 HTTP/1.1 200 OK 响应,其响应体类似于以下内容:

{
"id": 1,
"category": { "id": 1, "name": "Dogs" },
"name": "doggie",
"photoUrls": ["string"],
"tags": [{ "id": 1, "name": "tag1" }],
"status": "available"
}

获取详细的错误响应

此示例演示了如何在验证失败时获取详细的错误响应。

创建一个使用 OAS Validator 插件的路由:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "body_validation",
"uri": "/*",
"plugins": {
"oas-validator": {
"spec": "'"${OPEN_API_SPEC}"'",
"verbose_errors": true
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"petstore3.swagger.io:443": 1
},
"scheme": "https",
"pass_host": "node"
}
}'

使用无效的请求体向上面创建的路由发送请求:

curl -i "http://127.0.0.1:9080/api/v3/pet" -X POST \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{"invalid-body": "this is an invalid body"}'

你应该会看到 HTTP/1.1 400 Bad Request 响应,其响应体类似于以下内容:

doesn't match schema #/components/schemas/Pet: Error at "/name": property "name" is missing
Schema:
{
"properties": {
"category": {
"$ref": "#/components/schemas/Category"
},
"id": {
"example": 10,
"format": "int64",
"type": "integer"
},
...
}

Value:
{
"invalid-body": "this is an invalid body"
}
| Error at "/photoUrls": property "photoUrls" is missing
Schema:
{
"properties": {
"category": {
"$ref": "#/components/schemas/Category"
},
...
}

Value:
{
"invalid-body": "this is an invalid body"
}