Skip to the workspace
Pebellslearn by building
The Schema  ›  Lesson

Interfaces

Interfaces 14 minAn interface declares fields that several object types promise to implement, so a field can return any of those types, shared fields can be selected directly and type-specific fields are reached with inline fragments.

graphql / Interfaces

Explore each scene at your own pace.

01 · The rule

The rule

Interfaces

The bookshop starts selling magazines. A magazine has an ID, a title and a price, just like a book, but no author: it has an issue number instead. The home page wants one "new arrivals" list mixing both. An interface lets one field return either, while guaranteeing the fields they share.

The rule

An interface promises shared fields; ask for extras with ... on Type.

Declare the shared fields once, then have each object type implement the interface:

interface Product {
  id: ID!
  title: String!
  price: Float!
}

type Book implements Product {
  id: ID!
  title: String!
  price: Float!
  author: Author!
}

type Magazine implements Product {
  id: ID!
  title: String!
  price: Float!
  issue: Int!
}

type Query {
  newArrivals(first: Int = 10): [Product!]!
}

The rules for implementing:

  • A type must include every field of the interface, with the same arguments and a compatible type (the same type, or a stricter one such as String! for String).
  • It may add fields of its own, like author or issue.
  • A type can implement several interfaces: type Book implements Product & Node.

When a field returns an interface, you can select the shared fields directly. For type-specific fields, use an inline fragment with a type condition, and add __typename so the client knows what each item is:

{
  newArrivals {
    __typename
    title
    price
    ... on Book { author { name } }
    ... on Magazine { issue }
  }
}
{ "data": { "newArrivals": [
  { "__typename": "Book", "title": "The Salt Road", "price": 499, "author": { "name": "Mira Kapoor" } },
  { "__typename": "Magazine", "title": "Readers Monthly", "price": 120, "issue": 42 }
] } }

On the server, the interface needs one extra piece of code: a way to tell, for each value, which concrete type it is (often called resolveType).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.