Interfaces

GraphQL Interfaces represent a list of named fields and their arguments. GraphQL objects can then implement an interface, which guarantees that they will contain the specified fields.

Fields on a GraphQL interface have the same rules as fields on a GraphQL object; their type can be Scalar, Object, Enum, Interface, or Union, or any wrapping type whose base type is one of those five.

For example, an interface may describe a required field and types such asPersonorBusinessmay then implement this interface.

interface NamedEntity {
  name: String
}

type Person implements NamedEntity {
  name: String
  age: Int
}

type Business implements NamedEntity {
  name: String
  employeeCount: Int
}

Fields which yield an interface are useful when one of many Object types are expected, but some fields should be guaranteed.

To continue the example, aContactmight refer toNamedEntity.

type Contact {
  entity: NamedEntity
  phoneNumber: String
  address: String
}

This allows us to write a query for aContactthat can select the common fields.

{
  entity {
    name
  }
  phoneNumber
}

When querying for fields on an interface type, only those fields declared on the interface may be queried. In the above example,entityreturns aNamedEntity, andnameis defined onNamedEntity, so it is valid. However, the following would not be a valid query:

{
  entity {
    name
    age
  }
  phoneNumber
}

becauseentityrefers to aNamedEntity, andageis not defined on that interface. Querying forageis only valid when the result ofentityis aPerson; the query can express this using a fragment or an inline fragment:

{
  entity {
    name
    ... on Person {
      age
    }
  },
  phoneNumber
}

Result Coercion

The interface type should have some way of determining which object a given result corresponds to. Once it has done so, the result coercion of the interface is the same as the result coercion of the object.

Input Coercion

Interfaces are never valid inputs.

results matching ""

    No results matching ""