TExcelTAD
Home › GraphQL › Schema Design Best Practices

Schema Design Best Practices

A GraphQL schema is a long-lived public contract. Clients (mobile apps that users don't update for months!) depend on every field you ship. Good design makes the API pleasant to use and easy to evolve without breaking anyone. Here are the practices most teams converge on.

1. Design for clients, not for tables

Name things the way the product talks about them, and hide storage details:

Instead of Prefer Why
user_tbl, usr_nm User, name types and fields are product concepts
authorId: ID author: User let clients traverse the graph
status: Int (1, 2, 3) status: OrderStatus (enum) self-documenting, validated
priceCents: Int and priceCurrency: String price: Money (object with amount, currency) values that belong together, stay together

2. Naming conventions

  • Types: PascalCase (BlogPost). Fields and arguments: camelCase (createdAt). Enum values: SCREAMING_SNAKE_CASE.
  • Mutations: verb first, createPost, publishPost, addItemToCart, rather than generic updatePost for everything.
  • Booleans read as questions: isPublished, hasNextPage, canEdit.

3. Specific mutations with input and payload types

Give each mutation a single input argument and a dedicated payload type. Both can grow later without breaking clients, and the payload can carry user-facing errors:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Post { id: ID!, title: String!, published: Boolean! }

  input CreatePostInput { title: String!, body: String! }

  type UserError { field: String, message: String! }

  type CreatePostPayload {
    post: Post
    userErrors: [UserError!]!
  }

  type Query { posts: [Post!]! }
  type Mutation { createPost(input: CreatePostInput!): CreatePostPayload! }
`);

const posts = [];

const rootValue = {
  posts: () => posts,
  createPost: ({ input }) => {
    const userErrors = [];
    if (input.title.trim().length < 5) userErrors.push({ field: 'title', message: 'Title must have at least 5 characters.' });
    if (input.body.trim() === '') userErrors.push({ field: 'body', message: 'Body cannot be empty.' });
    if (userErrors.length) return { post: null, userErrors };
    const post = { id: String(posts.length + 1), title: input.title, published: false };
    posts.push(post);
    return { post, userErrors };
  },
};

const mutation = `mutation Create($input: CreatePostInput!) {
  createPost(input: $input) {
    post { id title }
    userErrors { field message }
  }
}`;

for (const input of [{ title: 'Hi', body: '' }, { title: 'Designing schemas', body: 'Start with the client.' }]) {
  const result = await graphql({ schema, rootValue, source: mutation, variableValues: { input } });
  console.log(JSON.stringify(result.data.createPost));
}
{"post":null,"userErrors":[{"field":"title","message":"Title must have at least 5 characters."},{"field":"body","message":"Body cannot be empty."}]}
{"post":{"id":"1","title":"Designing schemas"},"userErrors":[]}

The form can show userErrors next to the right fields, while top-level errors stay reserved for real failures.

4. Evolve, don't version

GraphQL APIs typically have no /v2. Instead you add fields and deprecate old ones. Adding is safe; removing or changing is not:

Change Safe for existing clients?
Add a type, a field, or an optional argument yes
Add an enum value mostly (clients must handle unknown values)
Make an output field non-null (String → String!) yes
Remove or rename a field no (deprecate first)
Make an output field nullable (String! → String) no
Add a required argument no

graphql-js can compute this list for you with findBreakingChanges, which is great in CI:

js · try it yourself
import { buildSchema, findBreakingChanges, findDangerousChanges } from 'graphql';

const before = buildSchema(`
  enum Plan { FREE PRO }
  type User { id: ID!, name: String!, email: String, plan: Plan! }
  type Query { user(id: ID!): User }
`);

const after = buildSchema(`
  enum Plan { FREE PRO TEAM }
  type User { id: ID!, fullName: String!, email: String!, plan: Plan }
  type Query { user(id: ID!, locale: String!): User }
`);

for (const change of findBreakingChanges(before, after)) console.log('BREAKING ', change.description);
for (const change of findDangerousChanges(before, after)) console.log('DANGEROUS', change.description);
BREAKING  User.name was removed.
BREAKING  User.plan changed type from Plan! to Plan.
BREAKING  A required arg locale on Query.user was added.
DANGEROUS TEAM was added to enum type Plan.

Making email non-null and adding fullName are not reported: both are safe for existing clients. The safe way to rename name to fullName: add fullName, mark name with @deprecated(reason: "Use fullName."), watch your field-usage metrics until no client asks for name, then remove it.

5. Nullability with intent

Default to nullable for fields that depend on other services or permissions; make identifiers, timestamps and lists non-null. A list should be [Item!]! (empty when there's nothing) rather than null.

6. Paginate anything that can grow

If a list can exceed a few dozen items, make it a connection (first/after) from day one. Turning comments: [Comment!]! into a paginated field later is a breaking change.

7. Global ids and node

Many APIs give every object a globally unique id (for example base64 of "Post:42") and a node(id: ID!): Node root field. Clients can then refetch any object by id, which normalized caches and Relay rely on.

8. Don't expose your internals

  • No generic query(sql: String) or filter: JSON escape hatches: they bypass the type system and invite abuse.
  • No fields that exist only because a table has a column.
  • Expose capabilities, not implementation: canEdit: Boolean! beats sending the raw ACL to the client.

Test yourself

Which change is safe for existing clients?

  1. Removing a field
  2. Adding a new optional field
  3. Adding a required argument
  4. Changing String! to String on an output

What's the recommended way to rename a field?

  1. Rename it and bump the API to /v2
  2. Add the new field, deprecate the old one, remove it once unused
  3. Change it silently
  4. Use an alias on the server

Why return a payload type like CreatePostPayload from a mutation?

  1. Mutations can't return object types
  2. It can grow later and can carry user errors next to the result
  3. It makes mutations run in parallel
  4. It's required by graphql-js