我想使用 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;
}
当您使用装饰器时,您本质上是在扩展现有的服务代码。 首先,您获取路径,然后使用给定的代码在 swagger 上下文中设置自定义操作。
如果您注意到代码块:
$openApi->getPaths()->addPath('/api/grumpy_pizzas/{id}', $pathItem->withGet(
$operation->withParameters(array_merge(
$operation->getParameters(),
[new Model\Parameter('fields', 'query', 'Fields to remove of the output')]
))
));
路径项采用 Operation 对象作为参数,该对象具有
withResponses
方法,可用于修改路径生成的任何响应。
将此作为每个光标,您可以检查整个源代码并查看最适合您的要求的内容。检查来源:PathItem.php
您可以根据 Response 对象构建响应并将其添加到操作和路径中。
提示:任何具有良好 linter 的编辑器都会使您的编码变得更容易,因为它将能够向您显示可用的方法。