Introduction to Querying with Arguments in GraphQL
Introduction to Querying with Arguments in GraphQL
In our previous lessons, we've discussed setting up a basic GraphQL server using Apollo Server and creating basic types and queries. In this lesson, we will focus on querying with arguments in GraphQL, which allows you to retrieve specific data based on the parameters you provide.
To understand querying with arguments, consider that you might want to fetch details about a specific book from a large collection. Instead of retrieving all books and filtering on the client side, you can pass an argument to your query to get just the book you need directly from the server.
Defining the GraphQL Schema with Arguments
To query specific data, we need to extend our GraphQL schema to include arguments. Recall from previous lessons that the schema defines the types of data and the shape of our queries.
Here’s how we define a schema with arguments:
In this schema:
- The
Booktype has three fields:id,title, andauthor. - The
Querytype contains two fields:books, which returns an array ofBookitems.book, which takes anidargument of typeID!and returns a singleBook.
Note that the ! symbol in ID!, String!, and other types signifies that these fields are non-nullable. This means that a value for these fields must always be provided and cannot be null. For instance, an id of type ID! must always have a value in any Book object.
Creating Resolvers for Queries with Arguments
Resolvers are functions that return data for the fields defined in your schema. When dealing with arguments, resolvers use these arguments to fetch the specific data requested.
Here are the resolvers for our schema:
Resolvers receive two main inputs:
parent(_in the code): Represents the result of the previous resolver in the chain (the "parent" or "root" value) . By using_, we signal that we're aware of this parameter but don't need it for our logic.args: An object containing the arguments passed to the query (e.g.,id).
In the above code:
- The
booksresolver returns the entire list of books. - The
bookresolver takes anidargument and returns the book that matches the givenid.
