0
0
GraphQLquery~30 mins

Interface types in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
GraphQL Interface Types Project
📖 Scenario: You are building a simple GraphQL API for a library system. The library has different types of items: books and magazines. Both share some common fields like id and title, but also have their own unique fields.
🎯 Goal: Create a GraphQL schema using interface types to define common fields for library items, then implement two types Book and Magazine that implement this interface. Finally, create a query to fetch all library items.
📋 What You'll Learn
Define an interface called LibraryItem with fields id (ID!) and title (String!)
Create a type Book that implements LibraryItem and adds a author field (String!)
Create a type Magazine that implements LibraryItem and adds an issueNumber field (Int!)
Create a query libraryItems that returns a list of LibraryItem interface
💡 Why This Matters
🌍 Real World
Interfaces in GraphQL help model real-world entities that share common features but also have unique details, like different types of library items.
💼 Career
Understanding GraphQL interfaces is important for building flexible and scalable APIs that serve diverse data types with shared structure.
Progress0 / 4 steps
1
Define the LibraryItem interface
Create a GraphQL interface called LibraryItem with two fields: id of type ID! and title of type String!.
GraphQL
Need a hint?

Use the interface keyword followed by the interface name and define the fields inside curly braces.

2
Create the Book and Magazine types implementing LibraryItem
Create a type called Book that implements LibraryItem and adds a field author of type String!. Also create a type called Magazine that implements LibraryItem and adds a field issueNumber of type Int!.
GraphQL
Need a hint?

Use the type keyword with implements LibraryItem and add the extra fields inside the type.

3
Add the libraryItems query returning a list of LibraryItem
Add a Query type with a field called libraryItems that returns a list of LibraryItem interface (use square brackets and exclamation mark for non-null list).
GraphQL
Need a hint?

Define a Query type with a field returning a non-null list of non-null LibraryItem.

4
Complete the schema with a union resolver placeholder
Add a placeholder comment inside the schema for resolvers to handle the LibraryItem interface type resolution (e.g., __resolveType). This completes the schema structure for interface usage.
GraphQL
Need a hint?

Resolvers for interfaces need a __resolveType function to tell GraphQL which type to use.