First Schema & Query
Every GraphQL API has two halves:
- A schema, written in the GraphQL Schema Definition Language (SDL), that lists the types and fields clients may ask for.
- Resolvers: the functions that produce a value for each field.
When a query arrives, the engine checks it against the schema, then calls resolvers to fill in the answer.
Writing a schema
The SDL is short and readable. A type has a name and a list of fields, and each field has a type:
type Query {
appName: String
version: Int
isBeta: Boolean
}Query is special: it is the root type for reads. Every query starts at one of its fields. The words String, Int and Boolean are built-in scalar types (there are five, covered later).
Running it with graphql-js
In JavaScript, buildSchema turns SDL text into a schema object, and graphql() executes a query against it:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Query {
appName: String
version: Int
isBeta: Boolean
}
`);
// The root value answers the fields of Query.
const rootValue = {
appName: 'Bookshelf',
version: 3,
isBeta: () => false, // a function is called to get the value
};
const result = await graphql({
schema,
source: '{ appName version isBeta }',
rootValue,
});
console.log(JSON.stringify(result, null, 2));{
"data": {
"appName": "Bookshelf",
"version": 3,
"isBeta": false
}
}
A few things to notice:
- A root-value entry can be a plain value (
'Bookshelf') or a function (() => false). graphql-js calls functions for you. - The result is an object with a
datakey, anddatahas exactly the shape of the query. graphql()returns a Promise, so weawaitit. Resolvers may beasync, too.
Query syntax
A query is a selection set: field names inside curly braces. These three are equivalent:
{ appName version }
query { appName version }
query GetInfo {
appName
version
}The short form { … } is an anonymous query. Adding the query keyword and a name (GetInfo) is good practice in real apps: names show up in server logs and dev tools. Commas and whitespace are optional and ignored; # starts a comment.
When the query is wrong
GraphQL validates every query before running it. Asking for a field that doesn't exist returns an errors list and no data:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Query {
appName: String
version: Int
}
`);
const result = await graphql({
schema,
source: '{ appName versoin }', // typo!
rootValue: { appName: 'Bookshelf', version: 3 },
});
for (const error of result.errors) {
console.log(error.message);
}
console.log('data' in result);Cannot query field "versoin" on type "Query". Did you mean "version"?
false
The helpful "Did you mean" hint comes from the schema: the server knows every valid field name.
Tip: Printing
JSON.stringify(result, null, 2)gives you exactly what an HTTP client would receive. A bareconsole.log(result)also works, but graphql-js builds objects without a prototype, so Node-style output shows[Object: null prototype]labels.
Printing a schema
You can turn a schema object back into SDL with printSchema. This is handy to check what you built:
import { buildSchema, printSchema } from 'graphql';
const schema = buildSchema(`
type Query { appName: String, version: Int }
`);
console.log(printSchema(schema));type Query {
appName: String
version: Int
}
Test yourself
What is the name of the root type that every read operation starts from?
- Root
- Query
- Schema
- Read
What does graphql-js do with a root-value entry that is a function?
- Returns the function's source code
- Calls it and uses the return value
- Throws an error
- Ignores the field
What does a result contain when the query asks for a field that doesn't exist?
datawithnullfor that field- An
errorslist and nodata - An empty object
- Only the valid fields