Fetching External Data Using REST API

Learn how to fetch external data at runtime using REST API in Gatsby.

Fetching data in real-time

Until now, we’ve looked at how to fetch data that is stored within our project and in content management systems using GraphQL and source plugins. This data is fetched and processed at build time. The issue with this is that some of the data in the database might change after building the project and when the application runs, leaving our site with stale data.

Note: Source (and some other) plugins have a way to keep fetching data in real time to keep the site updated.

Now, we look at fetching data hosted on an external server or environment using REST API. The code for this lives in the components where we wish to fetch and use this data. This data is fetched in real time. This means that it is fetched each time we visit (render) the page or component.

We can do this because Gatsby works with React under the hood. So, we can still use some of React’s API and hooks like useState and useEffect.

What we’ll do

To demonstrate this, we use the Github REST API endpoint to fetch and display our latest five projects on Github on our “Works” page.

Setting up

For our project repositories, we use this API endpoint:

https://api.github.com/users/${GITHUB_USERNAME}/repos?per_page=5&page=1&sort=updated

This endpoint returns the latest five public projects of the user sorted by their updated times.

Writing the code

We replace the existing code in the works.js file with the code below:

Get hands-on with 1200+ tech skills courses.