OpenAPI

PostgREST 在根路径上自动提供完整的 OpenAPI 描述。这提供了所有端点(表、外部表、视图、函数)的列表,以及支持的 HTTP 动词和示例有效负载。

注意

默认情况下,此输出取决于 JWT 角色声明中包含的角色的权限(或 db-anon-role 如果没有发送 JWT)。如果您需要显示所有端点,而不考虑角色的权限,请将 openapi-mode 配置设置为 ignore-privileges

为了实现更多自定义功能,OpenAPI 输出包含每个 SQL 注释 的“description”字段,无论该注释位于哪个数据库对象上。例如:

COMMENT ON SCHEMA mammals IS
  'A warm-blooded vertebrate animal of a class that is distinguished by the secretion of milk by females for the nourishment of the young';

COMMENT ON TABLE monotremes IS
  'Freakish mammals lay the best eggs for breakfast';

COMMENT ON COLUMN monotremes.has_venomous_claw IS
  'Sometimes breakfast is not worth it';

这些不友好的注释将在生成的 JSON 中以字段的形式出现,例如 info.descriptiondefinitions.monotremes.descriptiondefinitions.monotremes.properties.has_venomous_claw.description

此外,如果您希望生成一个 summary 字段,您可以通过使用多行注释来实现。第一行将作为 summary,后续行将作为 description

COMMENT ON TABLE entities IS
  $$Entities summary

  Entities description that
  spans
  multiple lines$$;

类似地,您可以通过对模式进行注释来覆盖 API 标题。

COMMENT ON SCHEMA api IS
$$FooBar API

A RESTful API that serves FooBar data.$$;

如果您需要包含 securitysecurityDefinitions 选项,请将 openapi-security-active 配置设置为 true

您可以使用像 Swagger UI 这样的工具,从描述中创建漂亮的文档,并托管一个交互式的基于 Web 的仪表板。该仪表板允许开发人员对实时 PostgREST 服务器发出请求,并提供有关请求头和示例请求主体的指导。

重要

当正在运行的服务器下的模式发生变化时,OpenAPI 信息可能会过时。请参阅 模式缓存重新加载

覆盖完整的 OpenAPI 响应

您可以使用函数结果覆盖整个默认响应。为此,请在 db-root-spec 上设置函数。

db-root-spec = "root"
create or replace function root() returns json as $_$
declare
openapi json = $$
  {
    "swagger": "2.0",
    "info":{
      "title":"Overridden",
      "description":"This is a my own API"
    }
  }
$$;
begin
  return openapi;
end
$_$ language plpgsql;
curl http://localhost:3000
HTTP/1.1 200 OK

{
  "swagger": "2.0",
  "info":{
    "title":"Overridden",
    "description":"This is a my own API"
  }
}