Interfaces are similar to Unions in that they provide a mechanism for dealing with different types of data. However, an interface is more suited for data types that include many of the same fields. In this lesson, we will query different types of pets.
To follow along with these queries, go to the Pet Library GraphQL Playground.
Interface:
# Write your query or mutation here
query {
totalPets,
availablePets,
checkedOutPets,
allAvailablePets {
__typename,
...PetDetail,
# only related to CAT
... on Cat {
sleepAmount
},
# only related to Rabbit
... on Rabbit {
favoriteFood,
floppy
},
# only related to Stingray
... on Stingray {
fast
}
}
}
fragment PetDetail on Pet {
name,
weight,
status,
photo {
thumb
}
}
Data return:
{ "data": { "totalPets": 25, "availablePets": 23, "checkedOutPets": 2, "allAvailablePets": [ { "__typename": "Cat", "name": "Biscuit", "weight": 10.2, "status": null, "photo": { "thumb": "https://www.catis.life/placeholder/200" }, "sleepAmount": 21 }, ... }