Defining Interfaces in GraphQL Schema
We define an interface with the help of the “interface” keyword in a GraphQL Schema, followed by an interface name, and the fields that we want to list out and be represented by it.
Example –
In the below example, we will create an Animal interface, which is a collection of ID, name, and species fields. This interface is then used by other interfaces, Dog and Cat, to inherit all the fields of the Animal interface, with some additional fields of their own.
interface Animal {
id: ID!
name: String!
species: String!
}
type Dog implements Animal {
id: ID!
name: String!
species: String!
breed: String!
}
type Cat implements Animal {
id: ID!
name: String!
species: String!
color: String!
}
Interfaces in GraphQL Schema
GraphQL is a powerful open-source query language for APIs. It is known for its flexibility and efficiency in fetching data from server endpoints. Unlike traditional REST APIs, which often have multiple endpoints for different resources, GraphQL typically exposes a single endpoint that allows clients to request exactly the data they need.
Interfaces in GraphQL help create a common set of fields and types that can be reused by other types or Queries. In this article, we will learn about the interfaces in GraphQL Schema.