Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Query a GraphQL API with graphql-request

    Alex BanksAlex Banks

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 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.

    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.

    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.

    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.

    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.