Skip to content

Schema-first GraphQL: write the schema, lint it, mock it, call it

Last checked and updated

Schema-first GraphQL means the schema in SDL is written, reviewed and agreed before any resolver exists; the server is then built to match it, and clients can start at the same time against a mock. The loop is short: write schema.graphql, check it with apigit lint schema.graphql, serve it with apigit mock serve schema.graphql, and call the mock with real queries while you change the schema. All three run offline, without an account.

1. Write the schema

"""A book in the catalog."""
type Book {
  id: ID!
  title: 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!
}

The schema is also the documentation: the strings before types and fields are descriptions (GraphQL schema documentation).

2. Lint it

$ apigit lint schema.graphql
No problems found.

A syntax mistake is an error that fails the run, an unknown type or a duplicate name is a warning (GraphQL syntax errors). The linter does not require a query root, because a file may be one part of a larger schema:

$ apigit lint types-only.graphql
No problems found.

The mock does require one. The specification: "The query root operation type must be provided and must be an Object type."

$ apigit mock serve types-only.graphql --port 4672
error: the document cannot be served: {"type":"https://apigit.com/mock/problems/unsupported-mock","title":"Unsupported mock","status":502,"detail":"The schema types-only.graphql has no Query type."}

3. Mock it

$ apigit mock serve schema.graphql --port 4671
GraphQL mock of schema.graphql at http://127.0.0.1:4671/graphql (Ctrl+C to stop). POST {"query": "..."} there, or GET with ?query=; the answers have the shape of the schema with made-up values.

Without --port it listens on 4010. It logs one line per request, such as POST /graphql -> 200.

4. Call it

A query, with an argument echoed into the field of the same name:

$ curl -s -X POST http://127.0.0.1:4671/graphql -H 'content-type: application/json' -d '{"query":"{ book(id: \"42\") { id title year author { name } } }"}'
{"data":{"book":{"id":"42","title":"Example","year":1,"author":{"name":"Example"}}}}

Variables and an operation name work; a list has two items:

$ curl -s -X POST http://127.0.0.1:4671/graphql -H 'content-type: application/json' -d '{"query":"query Search($t: String!) { searchBooks(text: $t) { title } }","variables":{"t":"git"}}'
{"data":{"searchBooks":[{"title":"Example"},{"title":"Example"}]}}

A mutation returns its type. title is echoed; authorId is not, because no field is called authorId:

$ curl -s -X POST http://127.0.0.1:4671/graphql -H 'content-type: application/json' -d '{"query":"mutation { addBook(title: \"Schema First\", authorId: \"7\") { id title author { id } } }"}'
{"data":{"addBook":{"id":"1","title":"Schema First","author":{"id":"1"}}}}

The mock validates every request against the schema; the specification's Validation section says that "execution should only occur for valid requests". A field the schema does not have, or a required argument left out, is refused with status 400 and a GraphQL errors list:

$ curl -s -i -X POST http://127.0.0.1:4671/graphql -H 'content-type: application/json' -d '{"query":"{ book(id: \"42\") { isbn } }"}'
HTTP/1.1 400 Bad Request
...
{"errors":[{"message":"Cannot query field \"isbn\" on type \"Book\".","locations":[{"line":1,"column":20}]}]}
$ curl -s -i -X POST http://127.0.0.1:4671/graphql -H 'content-type: application/json' -d '{"query":"{ searchBooks { title } }"}'
HTTP/1.1 400 Bad Request
...
{"errors":[{"message":"Field \"searchBooks\" argument \"text\" of type \"String!\" is required, but it was not provided.","locations":[{"line":1,"column":3}]}]}

That is the point of mocking the schema rather than hand-written JSON: a client cannot come to depend on a field that the schema, and later the server, does not have.

5. Change the schema while it runs

The mock follows the file. With isbn: String added to Book and the file saved, the query that was refused above is answered, without a restart:

$ curl -s -X POST http://127.0.0.1:4671/graphql -H 'content-type: application/json' -d '{"query":"{ book(id: \"42\") { isbn } }"}'
{"data":{"book":{"isbn":"string"}}}

A save that breaks the syntax (here isbn String, without the colon) does not stop the mock; requests get a problem response until the file parses again:

$ curl -s -i -X POST http://127.0.0.1:4671/graphql -H 'content-type: application/json' -d '{"query":"{ book(id: \"42\") { isbn } }"}'
HTTP/1.1 502 Bad Gateway
...
{"type":"https://apigit.com/mock/problems/unsupported-mock","title":"Unsupported mock","status":502,"detail":"The schema schema.graphql is not a valid GraphQL schema: Syntax Error: Expected \":\", found Name \"String\"."}

Stop it with Ctrl+C.

What the mock does not do

The values are fixed placeholders ("Example", 1, "string"), nothing is stored between requests, and subscriptions are not mocked. A GraphQL mock server from a schema file covers those limits, and the hosted mock that serves the same schema at a shared address. To keep the schema next to a REST API in one repository and publish both, see GraphQL and OpenAPI in one repository.

The loop in one table

StepCommandCatches
Writean editor
Lintapigit lint schema.graphqlsyntax errors (fail), unknown types and duplicates (warnings)
Mockapigit mock serve schema.graphqla schema without Query
Callcurl or the client being builtfields and arguments the client expects but the schema lacks
Reviewa pull request with the .graphql diffthe design itself

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