symfony - API 平台 - 如何使用装饰器在 Swagger UI 中添加响应代码以添加 400、404、500 响应代码,以便客户端提前知道响应
问题描述
我想使用 为 swagger UI 中的每条路线添加响应代码(400,404,500),以便用户提前知道这些错误代码的响应是什么。
我正在关注以下链接,但不确定如何修改 Response 对象并添加 400、404、401 等的响应。
https://api-platform.com/docs/core/openapi/#overriding-the-openapi-specification
我在写这个问题时使用的是 symfony 5.2 和 apiplatfrom 2.6。
解决方案
迟到了,但我得到了在我的 Swagger Ui 中添加响应代码的解决方案,它可以帮助一些寻找解决方案的人。
private function setErrorResponseDescriptions(OpenApi $openApi): OpenApi
{
$schemas = $openApi->getComponents()->getSchemas();
$schemas['Error'] = [
'type' => 'object',
'properties' => [
'type' => [
'type' => 'string',
'readOnly' => true,
],
'title' => [
'type' => 'string',
'readOnly' => true,
],
'detail' => [
'type' => 'string',
'readOnly' => true,
],
],
];
$schemas['ValidationError'] = [
'type' => 'object',
'properties' => [
'type' => [
'type' => 'string',
'readOnly' => true,
],
'title' => [
'type' => 'string',
'readOnly' => true,
],
'detail' => [
'type' => 'string',
'readOnly' => true,
],
'validations' => [
'type' => 'array',
'readOnly' => true,
'items' => [
'type' => 'object',
'properties' => [
'propertyPath' => [
'type' => 'string',
'readOnly' => true,
],
'message' => [
'type' => 'string',
'readOnly' => true,
],
]
]
]
],
];
foreach ($openApi->getPaths()->getPaths() as $path => $pathItem) {
foreach (['PUT', 'POST', 'PATCH', 'GET'] as $method) {
$item = $pathItem->{'get' . ucfirst($method)}();
if ($item) {
$item->addResponse(
new Model\Response(
description: 'Unauthorized',
content: new \ArrayObject([
'application/problem+json' => [
'schema' => [
'$ref' => '#/components/schemas/Error',
],
],
])
),
'401'
);
if ('GET' !== $method) {
$item->addResponse(
new Model\Response(
description: 'Bad request',
content: new \ArrayObject([
'application/problem+json' => [
'schema' => [
'$ref' => '#/components/schemas/ValidationError',
],
],
])
),
'400'
);
} else {
$item->addResponse(
new Model\Response(
description: 'Not Found',
content: new \ArrayObject([
'application/problem+json' => [
'schema' => [
'$ref' => '#/components/schemas/Error',
],
],
])
),
'404'
);
}
}
}
}
return $openApi;
}
推荐阅读
- html - 如何在 imagemagick 或其他工具上压缩 ico 文件
- ios - 有没有办法在视图中的多个子视图上调用函数?
- java - Java递归地填充一个对象
- javascript - 从 discord.js v12 上的文件中删除 JSON 对象
- apache-flink - 同时运行约 10 个批处理作业时,Flink 纱线会话模式变得不稳定
- javascript - 为什么电子中的 IpcRender 在构建到 .exe 文件后没有从 BrowserWindow.send() 获得任何值
- javascript - Vue Draggable - 如何仅替换选择的项目以防止移动网格上的所有其他项目?
- lua - 将相对于 obj1 的坐标转换为相对于 obj2
- firebase - 需要多次订阅 Firebase
- r - 意外错误 - 使用 glm 的回归模型