Skip to content

GraphQL and OpenAPI together: one repository, linted, mocked and published as one site

Last checked and updated

A REST API described in OpenAPI and a GraphQL API described in SDL can share one Git repository: they are reviewed in the same pull request, checked by one lint command, mocked from the same commit, and published as one documentation site. The repository below has an openapi.yaml, a schema.graphql, a Markdown overview and an apigit.json that puts them in one sidebar. An AsyncAPI file can join them the same way.

The repository

bookstore/
├── apigit.json
├── docs/
│   └── overview.md
├── openapi.yaml       # OpenAPI 3.1: GET /orders/{orderId}
└── schema.graphql     # GraphQL: Book, Author, Query, Mutation

The schema is the one from schema-first GraphQL, with an isbn field added. The OpenAPI file has one operation that returns an order.

openapi.yaml:

openapi: 3.1.0
info:
  title: Bookstore REST API
  version: 1.0.0
  description: Orders and payments over HTTP.
  contact:
    name: Bookstore team
    url: https://example.com/team
    email: team@example.com
  license:
    name: Apache 2.0
    identifier: Apache-2.0
servers:
  - url: https://api.example.com
tags:
  - name: orders
    description: Orders placed by customers.
paths:
  /orders/{orderId}:
    get:
      operationId: getOrder
      summary: Get an order
      description: Returns one order by its identifier.
      tags: [orders]
      parameters:
        - name: orderId
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: The order.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                  total:
                    type: number
        "404":
          description: No order with this identifier.

schema.graphql:

"""A book in the catalog."""
type Book {
  id: ID!
  title: String!
  isbn: String
  "Publication year."
  year: Int
  author: Author!
}

"""A person who wrote at least one book."""
type Author {
  id: ID!
  name: String!
}

type Query {
  "One book by its identifier, or null."
  book(id: ID!): Book
  "Books whose title contains the text."
  searchBooks(text: String!): [Book!]!
}

type Mutation {
  "Add a book and return it."
  addBook(title: String!, authorId: ID!): Book!
}

Lint both in one run

$ apigit lint openapi.yaml schema.graphql
No problems found.

Each file is checked by its format: the OpenAPI file with Spectral's OpenAPI rules, the .graphql file by parsing and validating the SDL. With one mistake in each (in openapi.yaml, two lines inserted after operationId: getOrder, line 22 security: and line 23 - apiKey: [], naming a scheme that is not defined; in schema.graphql, line 8 changed to author: Writer!, a type that does not exist):

$ apigit lint openapi.yaml schema.graphql
openapi.yaml
  23:18  warn   oas3-operation-security-defined  Operation "security" values must match a scheme defined in the "components.securitySchemes" object.  (paths./orders/{orderId}.get.security.0.apiKey)

schema.graphql
  8:11  warn   graphql-schema  Unknown type "Writer".

2 problems (0 errors, 2 warnings, 0 info, 0 hints)

Both are warnings, so the run passed with exit code 0. A GraphQL unknown type is a warning because a file can be part of a larger schema; when each schema is one complete file, fail on warnings:

$ apigit lint --fail-severity warn openapi.yaml schema.graphql
...
2 problems (0 errors, 2 warnings, 0 info, 0 hints)
error: lint failed: findings at severity warn or above

Mock both

Locally, apigit mock serve takes one file, so run two:

$ apigit mock serve openapi.yaml --port 4681
Mock of openapi.yaml at http://127.0.0.1:4681 (Ctrl+C to stop). 1 operation(s):
  GET /orders/{orderId}
$ apigit mock serve schema.graphql --port 4682
GraphQL mock of schema.graphql at http://127.0.0.1:4682/graphql (Ctrl+C to stop). POST {"query": "..."} there, or GET with ?query=; the answers have the shape of the schema with made-up values.
$ curl -s http://127.0.0.1:4681/orders/A-1
{"id":"string","total":0}
$ curl -s -X POST http://127.0.0.1:4682/graphql -H 'content-type: application/json' -d '{"query":"{ book(id: \"42\") { title author { name } } }"}'
{"data":{"book":{"title":"Example","author":{"name":"Example"}}}}

The hosted mock can serve both from one address. APIGit's documentation: "A hosted spec-based mock can serve a GraphQL schema alongside OpenAPI documents. The schema is another document of the same mock, with its own base path." --mount is repeatable; with --dry-run the command shows what it would send:

$ apigit --dry-run mock publish --name bookstore --type spec --mount openapi.yaml:/rest --mount schema.graphql:/graphql -R acme/bookstore
Using HEAD 7be1925 of the working directory (it must be pushed)
Would send POST /api/v1/app/mock/acme/bookstore/create
{
  "custom_domain": "bookstore",
  "commit_sha": "7be19252ccc4c817a045796e74559732c8f38736",
  "access_control": 0,
  "type": "spec",
  "mounts": [
    {
      "source": "openapi.yaml",
      "base_path": "/rest"
    },
    {
      "source": "schema.graphql",
      "base_path": "/graphql"
    }
  ]
}

One site, one sidebar

apigit.json in the repository root sets the navigation; a page entry names its file by its repository path:

{
  "nav": [
    { "name": "Overview", "slug": "overview", "file": "docs/overview.md" },
    {
      "name": "API reference",
      "slug": "reference",
      "children": [
        { "name": "REST API", "slug": "rest", "file": "openapi.yaml" },
        { "name": "GraphQL API", "slug": "graphql", "file": "schema.graphql" }
      ]
    }
  ]
}

apigit preview in the folder showed the sidebar Overview, then the group API reference with REST API and GraphQL API. /local/reference/rest showed the OpenAPI reference (title, description, contact, license, server, the orders tag and GET /orders/{orderId}), and /local/reference/graphql the GraphQL reference with its Queries (book, searchBooks), Mutations (addBook) and Objects (Book, Author). The slug is the entry's part of the page address.

Publishing makes that a version: "A version is a name pointing at a commit", and it contains "the OpenAPI specs, AsyncAPI documents and GraphQL schemas at that commit", the Markdown documents, and "the navigation and theme from that commit's apigit.json". In the browser that is Publish → Publish API & Doc; from a clone, after git push:

$ apigit --dry-run doc publish --version 1.0.0 -R acme/bookstore
Using HEAD 7be1925 of the working directory (it must be pushed)
Would send POST /api/v1/app/apispec/acme/bookstore/create
{
  "version": "1.0.0",
  "commit_sha": "7be19252ccc4c817a045796e74559732c8f38736",
  "access": 1,
  "enable_tryit": false
}

Without --dry-run it publishes; --access public makes the version public (the default is members only). Publish AsyncAPI documentation has the preview and publish steps in more detail.

What covers which format

OpenAPIGraphQL
apigit lintSpectral rulessyntax (errors) and schema checks (warnings)
apigit mock serve, hosted spec-based mockyesyes, at /graphql by default
Published reference, apigit.json navigationyesyes
Try It Out on the published pageyesno
apigit score, bundle, diff, breakingyesno

diff and breaking "Compare an OpenAPI document" (their help text). Pointed at two versions of the schema, they say so and stop with exit code 2:

$ apigit diff ../mixed/schema.graphql schema.graphql
error: ../mixed/schema.graphql is a GraphQL schema: apigit diff and breaking compare OpenAPI documents only

(Before CLI 0.9.1 they tried to read the schema as YAML and stopped with a parser error.) For a GraphQL schema, review the change in the pull request's diff, and keep the mock running against the branch so clients see a removed field as a 400 answer (schema-first GraphQL shows it).

Related: A GraphQL mock server from a schema file and Run a mock server from an OpenAPI file.

Sources

Related pages

Try it with your own API

Create a free workspace, add an OpenAPI file, and publish its documentation and a mock server from the same repository.

Free for individuals. No credit card.

$ npm install -g @apigit/cli$ apigit auth login$ apigit doc publish