Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

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

Autoplay

    Fetch Data from a GraphQL API

    Alex BanksAlex Banks
    apolloApollo
    graphqlGraphQL

    To query a GraphQL API, all you need to do is send an HTTP request that includes the query operation in the body of the request. In this lesson, we will use the browser’s fetch method to request the total days skied from our GraphQL API.

    Code

    Code

    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
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: First we're going to need an endpoint. We'll use localhost 4000.

    Next we're going to need a query, so we'll use this query for total days that we have right here running in the playground. Now we'll create some options for our fetch request. We'll use a post method.

    For the headers, we'll say that the content type is application JSON. Then we need to take this query and add it to the body, so I'm going to JSON stringify the query here.

    Now we can send a fetch request to our endpoint with our options. When we get a response from this endpoint, we'll go ahead and pluck the JSON out of the response. Then what will be returned to this next-then function is the actual data from the response in JSON.

    I'll go ahead and destructure that, and I should have our total days. We can create a string that has our total days and then pipe that along to a console log. If there's anything wrong, we can cache our errors and just log them using a console error.

    Now let's go ahead and start our client. I'll run NPM Start, and we'll see our application start up here in localhost 3000. We can see that we have our total days response. Right here, we see 100 days have been logged to the console.

    Let's take a quick look at what's going on here. In order to send a query to a GraphQL endpoint, we need the URL for the endpoint, and we also need the query itself. This is where we ask for the data that we want from the endpoint.

    After that, all we need to do is send an HTTP request, a post request that has the query inside of the body of the request. We should receive the data that we are asking for and the response under a field called Data.