0
0
GraphQLquery~30 mins

Search across types in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Search Across Types in GraphQL
📖 Scenario: You are building a simple search feature for a small online library. The library has two types of items: Books and Authors. Users want to search for a keyword that can match either a book title or an author name.
🎯 Goal: Create a GraphQL query that searches across both Book and Author types using a single search keyword. The query should return matching books with their title and year, and matching authors with their name and birthYear.
📋 What You'll Learn
Define GraphQL types Book and Author with specified fields
Create a SearchResult union type combining Book and Author
Write a search query that accepts a keyword argument
Return a list of SearchResult matching the keyword in either book titles or author names
Use inline fragments to select fields specific to Book and Author
💡 Why This Matters
🌍 Real World
Many applications need to search across different types of data, like books and authors, products and categories, or users and posts. This project shows how to do that in GraphQL.
💼 Career
Understanding how to use union types and inline fragments in GraphQL is important for building flexible APIs that serve complex search and filtering needs.
Progress0 / 4 steps
1
Define Book and Author Types
Define a GraphQL Book type with fields title (String) and year (Int). Also define an Author type with fields name (String) and birthYear (Int).
GraphQL
Hint

Use type keyword to define each type and list the fields with their types.

2
Create SearchResult Union Type
Create a GraphQL union type called SearchResult that combines the Book and Author types.
GraphQL
Hint

Use the union keyword followed by the union name and the types separated by |.

3
Add Search Query with Keyword Argument
Add a search query to the Query type. It should accept a keyword argument of type String! and return a list of SearchResult.
GraphQL
Hint

Define the Query type and add the search field with the correct argument and return type.

4
Write Search Query with Inline Fragments
Write a GraphQL query named SearchQuery that calls the search query with a variable $keyword of type String!. Use inline fragments to select title and year for Book, and name and birthYear for Author.
GraphQL
Hint

Use query keyword with variable declaration. Use inline fragments ... on TypeName to select fields for each type.