Overview
We can now query data from our REST API directly, but a list of featuredListings
is all we can ask about. Let's give our querying capabilities another option!
In this lesson, we will:
- Explore query arguments in GraphQL
- Add a new field to the
Query
type - Pass variables into a GraphQL query
Introducing query arguments
It's time to give our Query
type another entrypoint—and with it, a new feature for our API!
While we can get a list of the featured listings from our REST API, we don't yet have a way to ask for a specific listing's details. This single Query
entry point doesn't meet the needs of all our mockups; and our Listing
type is still missing a few fields to hold its description and amenities!
Querying the /listings/{listing_id}
endpoint
Let's return to our listings REST API endpoint. So far, we've only explored the GET /featured-listings
endpoint, but we have another option available for fetching a specific listing's data: GET /listings/{listing_id}
.
We can use this link to make a request for a specific listing. (Notice that we've passed in the value listing-1
in place of the query variable, {listing_id}
!)
https://rt-airlock-services-listing.herokuapp.com/listings/listing-1
Here's a snippet of some of the properties included in the response:
{"id": "listing-1","title": "Cave campsite in snowy MoundiiX","description": "Enjoy this amazing cave campsite in snow MoundiiX, where you'll be one with the nature and wildlife in this wintery planet. All space survival amenities are available. We have complementary dehydrated wine upon your arrival. Check in between 34:00 and 72:00. The nearest village is 3AU away, so please plan accordingly. Recommended for extreme outdoor adventurers.",// ... more listing properties"amenities": [{"id": "am-2","category": "Accommodation Details","name": "Towel"},{"id": "am-10","category": "Space Survival","name": "Oxygen"}// ... other amenities]}
Everything we need is here (along with some additional properties we'll put to use soon)!
To bring this functionality into our GraphQL API, we'll need to add another entry point to our schema. We'll be able to specify which unique listing we're querying for by giving this field an argument.
🤔 How to use arguments
An argument is a value you provide for a particular field in your query. The schema defines the arguments that each of your fields accepts.
Your datafetchers can then use a field's provided arguments to help determine how to populate the data for that field. Arguments can help you retrieve specific objects, filter through a set of objects, or even transform the field's returned value. A query that performs a search usually provides the user's search term as an argument.
To define an argument for a field in our schema, we add parentheses after the field name. Inside, we write the name of the argument followed by a colon, then the type of that argument, like String
or Int
. If we have more than one argument, we can separate them with commas.
Adding the listing
field
Pop open the schema.graphqls
file, and add the following field to the Query
type.
listing: Listing
We'll give the field a description, and then add parentheses after listing
to specify its argument: id
, of type ID!
.
"Returns the details about this listing"listing(id: ID!): Listing
And that's it for the query definition! We now have our schema up-to-date for the feature we're implementing. Onwards to our ListingService
: let's add a new method to hit this endpoint!
Updating the ListingService
Back in datasources/ListingService
, we'll make a new method called listingRequest
that can manage the call to the endpoint for a specific listing. It will receive a String
type variable called listingId
, and return an instance of ListingModel
.
public ListingModel listingRequest(String id) {}
This endpoint is still a GET
operation, we'll chain on a few methods: get()
, uri()
, and retrieve()
. The endpoint also requires a listing ID, so we'll include the listingId
we pass into this method as the second parameter to uri
.
public ListingModel listingRequest(String id) {return client.get().uri("/listings/{listing_id}", id).retrieve()}
Finally, we'll map the response to the ListingModel
class.
public ListingModel listingRequest(String id) {return client.get().uri("/listings/{listing_id}", id).retrieve().body(ListingModel.class);}
Note: Just as we did for the featuredListingsRequest
, we've made the name of listingRequest
extra verbose to avoid confusion with the listing
method on ListingDataFetcher
. These are separate methods, and we'll call this listingRequest
method from our listing
datafetcher shortly.
Using arguments in datafetchers
Now we can write the datafetcher method for our new Query.listing
field.
Open up datafetchers/ListingDataFetcher
. Here we'll add a new method for our listing
field, just below featuredListings
. Because this is still a Query
type field, we'll use the @DgsQuery
annotation.
// ...featuredListings method@DgsQuerypublic ListingModel listing() {}
When we query our GraphQL API for the listing
field, the id
argument we pass is automatically conveyed to this datafetcher. (Remember, the method's name, listing
, needs to match its corresponding Query
field exactly!)
To receive it, and actually do something with it, we'll specify that it receives an id
of type String
.
@DgsQuerypublic ListingModel listing(String id) {}
In order to clarify that this parameter corresponds with the id
input we specified in our schema's listing
field, we need to add a specific DGS annotation called @InputArgument
.
Let's import it...
import com.netflix.graphql.dgs.InputArgument;
...and update our method.
public ListingModel listing(@InputArgument String id) {}
Now we can call the new listingRequest
method on ListingService
! Inside of the listing
method, we'll pass in the id
argument and return the results.
@DgsQuerypublic ListingModel listing(@InputArgument String id) {return listingService.listingRequest(id);}
Let's test it out! Restart your server, then return to the Explorer to write out a new query.
Testing the listing
field
In the Documentation panel we'll see that our Query
type contains our new listing
field. When we click into it we can even see the name and the type of data it receives as an argument. Let's add a new workspace tab, then click the plus button beside the listing
field to add it to our query.
The Explorer automatically inserts some syntax for us to make completing the query easier.
Let's update our operation name to GetListing
to be extra clear about what we're doing with the data we request.
query GetListing($listingId: ID!) {listing(id: $listingId) {}}
You'll notice something new here: a dollar sign ($
) followed by the name listingId
.
The $
symbol indicates a variable in GraphQL. The name after the $
symbol is the name of our variable, which we can use throughout the query. After the colon is the variable's type, which must match the type of the argument we'll use it for. Variables are great—they let us pass argument values dynamically from the client-side so we don't have to hardcode values into our query. We'll use them every time we create a query with arguments.
In our case, we have a variable called listingId
that the Explorer set up for us down in the Variables section. Right now, it's set to null
, but let's replace it with the listing ID we've been testing so far: listing-1
.
Add the following to the Variables section in the Explorer:
{ "listingId": "listing-1" }
Let's test out our query by adding a few more fields for the listing we're after: title
and numOfBeds
.
The Operation panel of the Explorer should now look like this:
query GetListing($listingId: ID!) {listing(id: $listingId) {titlenumOfBeds}}
When we click on the run query button, we see the data we're expecting!
This works great, but we're still missing a couple of fields to complete our mock-up for an individual listing. When we check the REST API response for listings, we'll see that each listing JSON object contains a "description"
key; so let's go ahead and update our Listing
type to include this.
Back in schema.graphqls
, add the description
field shown below.
type Listing {id: ID!"The listing's title"title: String!"The listing's description"description: String!"The number of beds available"numOfBeds: Int!"The cost per night"costPerNight: Float!"Indicates whether listing is closed for bookings (on hiatus)"closedForBookings: Boolean}
We won't need to update our ListingModel
with this new property; when we restart our server, our generated Listing
type that ListingModel
extends will automatically become equipped with the new description
field.
But what about that list of amenities we see in our mock-up for a single listing?
We're still missing this data about each amenity—and even in our JSON response, it looks a bit more complicated than the schema fields we've explored so far—each amenity has an "id"
, "name"
, and "category"
!
{"id": "listing-1",// ... other listing properties"amenities": [{"id": "am-2","category": "Accommodation Details","name": "Towel"},{"id": "am-10","category": "Space Survival","name": "Oxygen"}// ... other amenities]}
Let's tackle bringing amenity data into our API in the next lesson.
Practice
Drag items from this box to the blanks above
datafetchers
!
schema
arguments
null
name
graph
@
$
hardcoded
Key takeaways
- Query arguments allow us to filter, customize, and further specify the data we'd like to query.
- We can refer to arguments passed directly into GraphQL fields with the DGS
@InputArgument
annotation. - We can use the
$
symbol in the Explorer to specify query variables.
Up next
In the next lesson, we'll explore how we build a relationship between object types—specifically, between our Listing
GraphQL type and a new type we'll call Amenity
.
Share your questions and comments about this lesson
This course is currently in
You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.