September 5, 2017

4 simple ways to call a GraphQL API

Sashko Stubailo
How-to

On this blog, we spend a lot of time pushing the limits of GraphQL and talking about some of the most advanced parts of the technology. However, GraphQL is inherently quite simple, and works just fine without any specialized tooling. So let’s demonstrate that by showing several very simple ways of calling a GraphQL API over HTTP.

The example API

For this post, we’ll want to use a small API that’s publicly accessible without any authentication to keep things as simple as possible. That’s exactly why we created Launchpad, a playground for building and deploying small GraphQL API examples. I’ll pick my favorite example from the list, the Authors and Posts example.

Every API on Launchpad has a built-in GraphiQL API explorer, as well as a public endpoint URL you can call from anywhere. In this case, the URL is:

https://1jzxrj179.lp.gql.zone/graphql

We’ll need this URL for the examples later.

1. GraphiQL

This is the tool we’ll start with because it will make it easy for us to compose queries we can slot into the tools below. GraphiQL is a React component that gives you a nice way to write GraphQL queries in your browser. It’s one of the best demonstrations of GraphQL’s self-documenting nature, since it auto-completes fields as you type!

Thankfully, GraphiQL is built right into Launchpad so we can just go there and start using it. Let’s try running a few queries. Here’s one you can start with:

query PostsForAuthor {
  author(id: 1) {
    firstName
    posts {
      title
      votes
    }
  }
}

And let’s also a try a one-line query which will be easier to use with some tools below:

{ posts { title } }

When you use GraphiQL, though, it can give the impression that you need a specialized tool to access data from your GraphQL API. So let’s go way back to basics.

Note from Jack MooreInsomnia is another great open source GraphQL API explorer to check out!

2. curl

curl is one of the most popular tools for accessing HTTP endpoints from the command line. It’s often used as a lowest-common-denominator example for how to access an API without any programming language or specialized tooling. So let’s use it to fetch GraphQL data!

Since curl is a command line tool, it’s easier to operate with queries that are just one line, so we’ll use the short one from above. Without further ado, here’s a curl command that will fetch a GraphQL query from our API:

curl \
  -X POST \
  -H "Content-Type: application/json" \
  --data '{ "query": "{ posts { title } }" }' \
  https://1jzxrj179.lp.gql.zone/graphql

It specifies four things about our request:

  1. The <strong>POST</strong> HTTP verb, which is the most common one used by GraphQL APIs (although usually GET is also supported)
  2. The content type of <strong>application/json</strong>, because we’re specifying the query as part of a JSON object
  3. The data sent, which is a JSON document that looks like: { "query": "{ posts { title } }" }. This JSON wrapper is helpful because you can also specify other options, like dynamic variables as part of the JSON object.
  4. The actual URL of the GraphQL endpoint, in this case <a href="https://1jzxrj179.lp.gql.zone/graphql." target="_blank" rel="noreferrer noopener">https://1jzxrj179.lp.gql.zone/graphql</a>.

And that’s all! Using the above options, you can query nearly any GraphQL API, for example the newly announced public API for Universe, which we’re using to manage tickets for GraphQL Summit:

curl \
  -X POST \
  -H "Content-Type: application/json" \
  --data '{ "query": "{ event(id: \"5983706debf3140039d1e8b4\") { title description } }" }' \
  https://www.universe.com/graphql/beta

Alright great, so we’ve found a completely vanilla way to send requests. For more details about exactly how GraphQL queries work, read my earlier post “The Anatomy of a GraphQL Query.”

3. JavaScript with fetch

You can make a GraphQL HTTP request in literally any programming language, as long as you can set the above 4 parts correctly. So let’s convert that curl request into some JavaScript code with fetch, the new standard for getting HTTP results with promises. This will work in modern browsers with no libraries, but will require a polyfill in Node and some browsers. Let’s check out the code:

require('isomorphic-fetch');

fetch('https://1jzxrj179.lp.gql.zone/graphql', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ query: '{ posts { title } }' }),
})
  .then(res => res.json())
  .then(res => console.log(res.data));

It’s pretty straightforward! As you can see, it’s pretty similar to the request we constructed with curl, but there are a few things here that would become pretty repetitive if we had to type them out every time. We could create our own helper functions, but it’s such a common need that we’ve done it for you:

4. JavaScript with apollo-fetch

apollo-fetch is a simple package that we’ve factored out of Apollo Client that just handles retrieving GraphQL results from an HTTP API. It makes the above simpler, especially for the case of running multiple queries:

const { createApolloFetch } = require('apollo-fetch');

const fetch = createApolloFetch({
  uri: 'https://1jzxrj179.lp.gql.zone/graphql',
});

fetch({
  query: '{ posts { title }}',
}).then(res => {
  console.log(res.data);
});

// You can also easily pass variables for dynamic arguments
fetch({
  query: `query PostsForAuthor($id: Int!) {
    author(id: $id) {
      firstName
      posts {
        title
        votes
      }
    }
  }`,
  variables: { id: 1 },
}).then(res => {
  console.log(res.data);
});

You can see that you don’t have to repetitively pass the same options multiple times, and it handles stuff like content type and parsing JSON for you. But it’s important to see that there’s no magic at all — you could easily write all of your GraphQL requests by hand, without any special libraries.


How does a GraphQL request look in your favorite language?

The above examples used JavaScript, but they should be easy to reproduce in Python, Ruby, Go, Java, or any other language where you can make HTTP requests. My favorite thing about GraphQL is that it’s compatible with so many different tools and approaches. So if you have a simple code snippet for running a query against a GraphQL API, post it as a response and we can compile a list comparing different ways to run the same query!

Written by

Sashko Stubailo

Stay in our orbit!

Become an Apollo insider and get first access to new features, best practices, and community events. Oh, and no junk mail. Ever.

Similar posts

September 23, 2020

Add GraphQL to Your Jetpack Compose Apps

by Martin Bonnin

Company