Build pages in Gatsby from Rest API

Banner image for Build pages in Gatsby from Rest API
Photo by Tamara Bitter on Unsplash

Creating pages in Gatsby is easy. But when we want the pages to be also part of the GraphQL layer so that we can query them in index pages, we need to hook into sourceNode() in the gatsby-node.js.

js
1// gatsby-node.js
2
3const fetch = require(‘node-fetch’;)
4
5// part one
6const createPages = async ({ actions }) => {
7 const { createPage } = actions;
8
9 const allPosts = await (await fetch(‘http://some-api.com/all’)).json();
10 for (const post of allPosts) {
11 const blocks = await (await fetch(‘http://some-api.com/post/+ post.id)).json();
12 createPage({
13 path: `writings/${post.Slug}`,
14 component: path.resolve(`./src/templates/post.js`),
15 context: {
16 slug: `writings/${post.Slug}`,
17 blocks,
18 },
19 });
20 }
21};
22
23// part two
24const sourceNodes = async ({ actions }) => {
25 const { createNode } = actions;
26
27 const allPosts = await (await fetch(‘http://some-api.com/all’)).json();
28 for (const post of allPosts) {
29 // create node for graphql
30 const node = {
31 id: `${post.Slug}`,
32 parent: `__SOURCE__`,
33 internal: {
34 // lets you query nodes using allAPIPost and APIPost
35 type: `APIPost`,
36 },
37 children: [],
38
39 // Other fields that you want to query with graphQl
40 slug: post.Slug,
41 title: post.Name,
42 date: post.Date,
43 draft: post.Draft,
44 };
45 const contentDigest = crypto.createHash(`md5`).update(JSON.stringify(node)).digest(`hex`);
46 node.internal.contentDigest = contentDigest;
47 createNode(node);
48 }
49};
50
51// module.exports = { createPages, sourceNodes };
52

Let me explain this. There are 2 parts to it.

  • One - creating the pages after fetching from the rest API using createPage()
  • Two - creating the node in the GraphQL layer to be able to query in other pages (for example in index.js where you list all the pages)

After adding that piece of code to gatsby-node.js and running gatsby develop you will have pages created at the path you’ve given to createPage().

To list them in any other page, we can use a query that looks like this

graphql
1query {
2 allPost(sort: { order: DESC, fields: date }) {
3 nodes {
4 slug
5 title
6 date
7 }
8 }
9}
10

You can experiment with the query in GraphiQL dashboard that runs when you gatsby develop.

Hope this helps.

Aravind Balla

By Aravind Balla, a Javascript Developer building things to solve problems faced by him & his friends. You should hit him up on Twitter!

Get letters from me 🙌

Get a behind-the-scenes look on the stuff I build, articles I write and podcast episodes which make you a more effective builder.

Read the archive 📬

One email every Tuesday. No more. Maybe less.