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 asPerson
orBusiness
may 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, aContact
might refer toNamedEntity
.
type Contact {
entity: NamedEntity
phoneNumber: String
address: String
}
This allows us to write a query for aContact
that 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,entity
returns aNamedEntity
, andname
is defined onNamedEntity
, so it is valid. However, the following would not be a valid query:
{
entity {
name
age
}
phoneNumber
}
becauseentity
refers to aNamedEntity
, andage
is not defined on that interface. Querying forage
is only valid when the result ofentity
is 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.