REST APIs in Gatsby at Runtime

Christina Hastenrath
4 min readApr 24, 2020

This is a step-by-step tutorial on how to call external REST APIs in Gatsby at runtime using Axios.

This tutorial assumes you already have a Gatsby App up and running. If you are new to Gatsby, they have a great starter tutorial and documentation.

The Gatsby docs describe how you can add a REST API call in your app at Buildtime. You do this by using the createPages API in the gatsby-node.js file.

For our use case, we wanted to call the REST API endpoint at Runtime instead. Our browsers take care of the caching, which is great because we do not have to do anything extra for that.

API response with Postman

Alright, first things first. When you receive the REST API endpoints, head over to your Postman Client to run a GET request and check that all data that you need is coming back. Postman has great docs if you would like to know more about how to set authorization for your API call.

Inside the Gatsby App

This is what our API endpoint looks like:

https://covid-19testing.github.io/locations/${state}/complete.json

In our example, we are going to hit several API endpoints with the same API call and create paths for each endpoint. Each ${state} variable will be a new endpoint and return a response with new data. We could have stored all of our response data in one API endpoint, but we decided to split up the endpoints to significantly increase our App’s performance.

Once you confirm the correct API response, open up your Gatsby App and navigate to gatsby-node.js. In here we are going to use the createPages API to create a page template for the API response data and the context API to pass each variable to our components.

/gatsby-node.js

This is what our code looks like in gatsby-node.js:

Christina Hastenrath

Molecular Biologist turned Software Engineer. I write about my code. Connect with me on Twitter @etTinchen