Query a GraphQL API with graphql-request

Alex Banks
InstructorAlex Banks
Share this video with your friends

Social Share Links

Send Tweet

Created by the team at Prisma, graphql-request is a lightweight package that can be used to send queries to any GraphQL API. Sending a request with graphql-request uses less syntax than a fetch request. In this lesson, we will query the totalDays field using this helper package.

Instructor: [00:01] I'm going to install a package called graphql-request. graphql-request provides an alternative to using the fetch method. Next, we're going to import the request function from the graphql-request package. I'll add a little log that notifies the user that we're sending the query.

[00:23] This request method is a wrapper around the fetch method. It will handle sending the options and parsing the response data. All we need to do is send an endpoint and a query, and we will get our data directly back in the response.

[00:36] I can destructure total days from data, and use that to construct my string. We'll log all of our results to the console, and we'll also catch any errors that occur and log them to the console as well. Now, we can open up the terminal, and start our client. We see the results right here in the console.

[00:59] There's our total days count, at 100. If we open up the network tab of our developer tools, we can actually see the HTTP request. This second localhost request is our HTTP request, so we can see the post request to our GraphQL service, and we can also see the data that has been returned.

[01:16] There's our total days. We are still sending an HTTP request, but instead of using Fetch to send the request, we've simplified the code quite a bit by using the request method from graphql-request.