Schema-first and code-first

Intermediate · 6 min

Author one schema two ways: write SDL and attach resolvers, or build types in code with graphql-js. Compare the output and when to pick each.

Before thisSchema definition languageResolvers

Jamie Barton · 6 min

Schema-first and code-first

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Jamie BartonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Schema-first means you write the schema in SDL and attach a resolver map to it; code-first means you build the types with a library's API, and the SDL is generated.
  • Both produce the same executable schema: the printed SDL of a hand-built graphql-js schema matches the SDL version apart from the order of the types.
  • Schema-first is readable by anyone and reviewable as a contract, but resolver types and the SDL can drift apart unless you generate types from the schema.
  • Code-first keeps types and resolvers in one place and lets the compiler check them, but the schema is harder to read and review at a glance, and verbose without a helper library.
  • Pick one per project and make the schema file the thing reviewers look at, whether it is hand-written or printed from code.

The problem: one schema, two ways to write it

The schema is the contract. Before you can resolve a single field, you must describe the types. There are two honest ways to do it, and teams argue about them more than the difference deserves.

Schema-first: write the SDL as text and bolt resolvers on.

Code-first: describe the types with functions and objects in your language. The SDL becomes output.

Both end in the same place, a GraphQLSchema object that the executor runs.

Schema-first

You have already seen this version:

import { createYoga, createSchema } from 'graphql-yoga';

const typeDefs = /* GraphQL */ `
  type Post { id: ID! title: String! }
  type Query { posts(limit: Int = 3): [Post!]! }
`;

const resolvers = {
  Query: { posts: (_, { limit }, { db }) => db.prepare('SELECT * FROM posts LIMIT ?').all(limit) },
};

const schema = createSchema({ typeDefs, resolvers });

Strengths: the SDL is the contract, in the language GraphQL clients and designers speak. A product manager can read it. A diff of the .graphql file shows exactly what changed for clients. You can design the schema before writing any implementation.

Weaknesses: the types in the SDL and the types in your resolver code are unrelated as far as the compiler is concerned. If the SDL says title: String! and your resolver returns an object without title, nothing complains until a client asks. A code generator that creates TypeScript types from the SDL fixes this; without one, you carry the risk.

Yoga does catch one class of mistake early. I added a resolver for a field the SDL does not define, and createSchema threw at startup: Query.b defined in resolvers, but not in schema. A typo in the SDL itself fails fast too: Unknown type "Strng". Did you mean "String"?

Code-first

The same schema, built with graphql-js’s type constructors:

import {
  GraphQLSchema, GraphQLObjectType, GraphQLNonNull, GraphQLList,
  GraphQLID, GraphQLString, GraphQLInt,
} from 'graphql';

const Post = new GraphQLObjectType({
  name: 'Post',
  fields: {
    id: { type: new GraphQLNonNull(GraphQLID) },
    title: { type: new GraphQLNonNull(GraphQLString) },
  },
});

const Query = new GraphQLObjectType({
  name: 'Query',
  fields: {
    posts: {
      type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(Post))),
      args: { limit: { type: GraphQLInt, defaultValue: 3 } },
      resolve: (_, { limit }, { db }) =>
        db.prepare('SELECT * FROM posts LIMIT ?').all(limit),
    },
  },
});

const schema = new GraphQLSchema({ query: Query });

The resolver sits beside its field, so there is no separate map to keep in sync. When I printed both schemas with printSchema, they contained the same two types and the same fields; the only difference was the order the types came out. Served through Yoga, { posts(limit: 2) { id title } } returned posts 1 and 2.

The cost is visible above: [Post!]! became new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(Post))). Raw graphql-js is the verbose end of code-first. Libraries wrap this in a typed builder; Pothos is a TypeScript-first example. I did not run Pothos for this lesson, so look at its documentation for the current API. With such a library the compiler checks that a resolver returns what the field type promises, which schema-first only gets with code generation.

Choosing

Schema-first Code-first
Schema is read as plain SDL code, SDL on demand
Resolver type safety needs codegen usually built in
Review the contract diff the .graphql print and commit the SDL
Learning curve the SDL you already know the library’s API

A practical rule: if clients, designers or other teams read your schema, start schema-first and add type generation. If your own TypeScript code is the only audience and you want the compiler to guard every field, code-first with a builder is comfortable. Mixed projects exist too, but one source of truth per schema is the safer default.

Whichever you pick, keep a printed schema file in version control. It is what tools like schema registries and CI checks compare to catch a breaking change before it ships. The next lessons use schema-first, with SDL strings, because the SDL is shorter to show.

What the video covers

Jamie Barton’s “Schema-first or code-first GraphQL” is a six-minute video from 2022. I could not read its description or a transcript, so this lesson rests on the title: a direct comparison of the two approaches. The GraphQL TV talk in the links below is a thirty-minute conference session on adopting schema-first development.

Where this fits

You can describe a schema either way, and the rest of the roadmap uses SDL. Next you put a real server around it. Next: a server with GraphQL Yoga.

Check yourself

  1. 01What does a schema-first project write by hand that a code-first project does not?

    The SDL, the `type Post { ... }` definitions. A code-first project writes types as objects in code, using something like `GraphQLObjectType`, and prints the SDL from them.

  2. 02What happens in Yoga if a resolver map names a field the SDL does not define?

    `createSchema` throws at startup, for example `Query.b defined in resolvers, but not in schema`, so a mismatched name fails fast instead of silently never running.

  3. 03What is the main drift risk of schema-first?

    The SDL says one thing and the resolver returns another, because nothing connects their types. Generating TypeScript types from the SDL closes the gap.

  4. 04Why do teams that go code-first still commit a printed schema file?

    Reviewers and clients can read and diff the SDL, and CI can detect breaking changes by comparing it with the previous version.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark