Creating Rest API endpoints to my Gatsby blog
Learn how to add API endpoints to Gatsby v3 using the onPostBuild method and create JSON files with a global variable
Written in January 22, 2023 - 🕒 3 min. readGatsby is a popular static site generator that is built on React, and it’s the one that I use to create this blog. With its powerful plugin system, it allows developers to easily add features to their sites.
One feature that can be added is API endpoints, which can be used to serve JSON data to the client.
In this post, we will look at how to add API endpoints to Gatsby v3 by modifying the gatsby-node.js
file.
First post of 2023, let’s go!!
The problem
In a Gatsby site, the data that is used to build pages is typically sourced from a variety of sources, such as Markdown
files or a headless CMS.
In my case, all my posts come from Markdown
files, and I have some custom scripts to match related posts, get the blog post comments, etc.
Since all my data is stored “offline”, if I want to access it in another application I would have to pretty much scrape my own website, and that’s not good.
The solution
If I create an API endpoint for my blog, then I can expose all data that is currently already public and displayed as HTML
, but provide it as a “raw” JSON data.
To add API endpoints to a Gatsby site, we need to take advantage of the onPostBuild
lifecycle method in the gatsby-node.js
file. This method is called after the site has been built, and allows us to perform additional actions, such as creating JSON files.
Since I do a lot of custom scripting on all my pages, we are using a global variable called jsonFiles
that will dynamically populate with data from the onCreatePage
function.
This will be used to store the data that we want to use to create the JSON files then loop through each path in the jsonFiles
object and use the createPage
action to create a new page for each path
.
Here is an example of how I’m doing it:
const { writeFileSync } = require('fs');
const jsonFiles = {};
exports.onCreatePage = ({ page }) => {
jsonFiles[page.path] = page.context.data;
}
exports.onPostBuild = () => {
Object.entries(jsonFiles).map(([filePath, content]) => {
const fileFullPath = path.resolve(
__dirname,
'public',
...filePath.split('/').filter((part) => part)
);
writeFileSync(fileFullPath, JSON.stringify(content));
});
}
Consuming the data from the API endpoints
Once the API endpoints have been created, the next step is to consume the data from the client side. This can be done by using the fetch()
function.
Here is an example of how to use fetch()
to get the data from the endpoint for this blog post:
fetch('https://pablo.gg/en/blog/coding/creating-rest-api-endpoints-to-my-gatsby-blog.json')
.then((response) => response.json())
.then((data) => {
console.log(data);
// { comments: [], html: '<p>..</p>', language: 'en', path: 'blog-path', postHashId: 'hash', relatedPosts: [], title: 'Post title' }
})
.catch((error) => console.log(error))
Conclusion
Adding API endpoints to a Gatsby site is a simple task, but can enhance the possibilities of your website.
I will soon (I hope) share what I plan to do with my own API 👀
That’s all I have for you guys today, see you on the next one!
Tags:
Related posts
Post a comment
Comments
No comments yet.