记录 GraphQL API

Document a GraphQL API

借助 REST,我们可以使用 Swagger、RAML 或其他技术来记录我们的 API 并生成 HTML 我们的消费者无需与服务器交互即可阅读的文档。

GraphQL 是否存在类似的东西?有什么方法可以生成资源和属性的文档吗?

据我所知,目前还没有工具可以自动为 GraphQL API 生成 HTML 文档,但我发现 GraphiQL 比任何 API 我看过 HTML 中的文档。

GraphiQL 允许您以交互方式探索 GraphQL 服务器的架构并同时 运行 对其进行查询。它具有语法高亮显示、自动完成功能,甚至可以在不执行查询的情况下告诉您查询无效。

如果您正在寻找静态文档,我发现使用 GraphQL 模式语言阅读模式非常方便。多亏了 GraphQL 的另一个强大功能——模式自省——你可以轻松地打印你有权访问的任何服务器的模式。简单地 运行 introspection query 针对服务器,然后像这样打印生成的内省模式(使用 graphql-js):

var graphql = require('graphql');
var introspectionSchema = {}; // paste schema here
console.log(graphql.printSchema(graphql.buildClientSchema(introspectionSchema)));

结果将如下所示:

# An author
type Author {
  id: ID!

  # First and last name of the author
  name: String
}

# The schema's root query type
type Query {

  # Find an author by name (must match exactly)
  author(name: String!): Author
}

现在好像有https://www.npmjs.com/package/graphql-docs

Dynamically generated documentation explorer for GraphQL schemas. It aims to provide a better overview of a schema than GraphiQL, but without querying features.

您还可以基于架构文件或 GraphQL 端点生成静态文档文件:

npm install -g graphql-docs
graphql-docs-gen http://GRAPHQL_ENDPOINT documentation.html

我找到了用于记录 GraphQL 模式的静态页面生成器。 GitHub link.

HTML 导出看起来像这样。

GitHub GraphQL doc example

实际上,Graphql 是通过 Facebook 的内置 Graphiql 或像 Altair 这样的第三方工具进行自我记录的,因为列出了 queries/mutations 并且还列出了 return 类型显示在那里。

我发现一个需要文档的地方是输入查询参数,它可能需要 specific format。这可以通过在 那些 arguments 之上添加注释 来实现。

  type Query {
      eventSearch(
        # comma separated location IDs. (eg: '5,12,27')
        locationIds: String,
        # Date Time should be ISO 8601: 'YYYY-DD-MM HH:mm:ss'. (eg: '2018-04-23 00:00:00')
        startDateTime: String!,
        endDateTime: String!): [Event]
  }

会像下面这样:

Graphiql:

牵牛星:

如果您是 Sphinx / ReadTheDocs 用户,您可能会发现 https://github.com/hasura/sphinx-graphiql 有用。

另一个最近的工具是 SpectaQL. The output can look like this。 引用自述文件:

Autogenerate static GraphQL API documentation.

SpectaQL is a Node.js library that generates static documentation for a GraphQL schema using a variety of options:

  1. From a live endpoint using the introspection query.
  2. From a file containing an introspection query result.
  3. From a file, files or glob leading to the schema definitions in SDL.

The goal of SpectaQL is to help you keep your documentation complete, current and beautiful with the least amount of pain as possible.

Out of the box, SpectaQL delivers a 3-column page with a modern look and feel. However, many aspects can be customized with ease, and just about everything can be customized if you're willing to dig in.

在过去的几个月里,我一直在为此积极研究新的解决方案,因为现有的解决方案不符合我的需求。它们不容易定制或根本无法维护。

https://github.com/magidoc-org/magidoc