TypeScript

Top GraphQL Interview Questions with Code Examples

I've been on both sides of GraphQL interviews — asking and answering. These are the questions that actually come up, with code examples that show you unde...

14 Apr 2024

Top GraphQL Interview Questions with Code Examples

I've been on both sides of GraphQL interviews — asking and answering. These are the questions that actually come up, with code examples that show you understand the concepts, not just the definitions.

What is GraphQL and how does it differ from REST?

GraphQL is a query language for APIs. The client asks for exactly the data it needs, nothing more.

With REST, you hit predefined endpoints that return fixed data shapes. Need a user's name but not their address? Too bad — the endpoint returns everything. With GraphQL, the client controls the response shape in a single request.

Explain GraphQL Schema and its types

A schema defines what data your API exposes and how it's structured.

Graphql
type User {
  id: ID!
  name: String!
  email: String!
}

type Query {
  user(id: ID!): User
}

Types include objects (User), scalars (String, Int, Float, Boolean, ID), enums, and interfaces.

What are scalar types?

Scalars are the leaf nodes of a query — primitive values that can't be broken down further.

Built-in scalars:

  • String — text
  • Int — 32-bit integer
  • Float — double-precision float
  • Boolean — true/false
  • ID — unique identifier, serialized as a string

You can define custom scalars for specific formats:

Graphql
scalar Date

type Event {
  id: ID!
  title: String!
  date: Date!
}

What is a resolver?

A resolver is the function that fetches data for a field. The schema defines the shape. The resolver fills it in.

Typescript
const resolvers = {
  Query: {
    user: (parent, { id }, context) => {
      return context.db.users.findById(id);
    }
  }
};

Every field in your schema can have its own resolver. If you don't provide one, GraphQL uses a default resolver that looks for a property with the same name on the parent object.

The trade-off with GraphQL

GraphQL gives clients flexibility. That's the benefit.

The cost: complexity moves to the server. You need to handle query depth limits, prevent N+1 queries with dataloaders, manage caching (which is harder than REST because every query is unique), and deal with a more complex error handling model.

REST is simpler for simple APIs. GraphQL pays off when you have multiple clients (web, mobile, third-party) with different data needs hitting the same backend.