Query a GraphQL API with graphql-request

Alex Banks
InstructorAlex Banks
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

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.

egghead
egghead
~ 45 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today