How to call a GraphQL API with Axios

Using a POST HTTP request

Sashko Stubailo
Mar 12, 2018 · 1 min read

Axios is an HTTP client library for JavaScript. If you’re building an app with React, Vue, or Angular, it’s useful to use a GraphQL client library like Apollo Client, but if you just need to make one GraphQL call, for example from a Node.js script, you can use any library you want. We’ve had a few questions about how to do it with Axios, so I thought I’d throw together a super quick example.

In this example we’re going to call the authors and posts server hosted on Launchpad. Go there to see the server code. The GraphQL API URL for that server is:

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

And the query we want to send is:

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

Now we can put those together into a simple POST request with Axios like so:

const axios = require("axios")axios({
url: 'https://1jzxrj179.lp.gql.zone/graphql',
method: 'post',
data: {
query: `
query PostsForAuthor {
author(id: 1) {
firstName
posts {
title
votes
}
}
}
`
}
}).then((result) => {
console.log(result.data)
});

Wow, that was simple! You can try that yourself by running the code in your browser using RunKit.

If you want to see examples with some other libraries, check out my previous post:

Thanks for reading!

Sashko Stubailo

Written by

engineer at @stripe. previously open source eng manager at @apollographql and @meteorjs, https://github.com/stubailo

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade