Kest

Search

Search the documentation

GraphQL

Interfaces

Several types that share fields.

An interface is a list of fields that several types promise to have. Ask for the shared fields on the interface, and for the specific ones with a fragment (... on Dog).

interface Animal { name: String! }
type Dog implements Animal { name: String!  barks: Boolean! }
type Cat implements Animal { name: String!  lives: Int! }
 
type Query { animals: [Animal!]! }
interface Animal { val name: String }
data class Dog(override val name: String, val barks: Boolean) : Animal
data class Cat(override val name: String, val lives: Int) : Animal
 
@Resolver class ZooResolver {
    @Query fun animals(): List<Animal> = listOf(Dog("Rex", true), Cat("Tom", 9))
}
{ animals { __typename name ... on Dog { barks } ... on Cat { lives } } }
{ "data": { "animals": [ { "__typename": "Dog", "name": "Rex", "barks": true }, { "__typename": "Cat", "name": "Tom", "lives": 9 } ] } }

How Kest knows which type an object is

When a field returns an interface (or a union), GraphQL must know the concrete type of each object. Kest decides from:

  1. the object's class name: a Dog object is the GraphQL type Dog (or the name given by @GqlType(name = "...") when generating the schema); or
  2. a __typename entry, when you return a map: mapOf("__typename" to "Dog", "name" to "Rex").

Anything else fails the query with a clear message saying to name the class after the type.

Code-first

You can generate these from annotations instead of writing the SDL: @GqlInterface on the Kotlin interface, see Generating SDL.

When to use one

Use an interface when types share behaviour a client cares about (every Node has an id, every Animal a name, every Event a timestamp). If the types share nothing, use a union.

Read more