- 11 min read
-
API
Tool
Gatsby
Serverless
Paul Scanlon shows you how to create an API using Gatsby Functions. He also explains what to do when you deploy it to Gatsby Cloud.
You’ve probably heard about Serverless Functions, but if you haven’t, Serverless Functions provide functionality typically associated with server-side technologies that can be implemented alongside front-end code without getting caught up in server-side infrastructures.
Front-end developers such as myself, can expand the possibilities of the tools and techniques they love and use to create client-side and server-side code.
Limitations
Coexistence is great but there are at least two scenarios I’ve encountered where using Serverless Functions in this way weren’t quite the right fit for the task at hand. These are
- The front end could not support Serverless Functions.
- The same functionality was needed by multiple front ends.
To give you some context, here is an example of each point 1 and 2. MDX Embed is an open-source project that I manage. You can see it on the Docs website. It’s definitely not a Gatsby site. This website was built with Storybook, and Storybook by itself does not have Serverless Function capabilities. To fund the project, I needed to make “Pay What You Want” payments. I used Stripe because it allowed me to securely pay my customers. However, this would have required a backend.
By abstracting the functionality into an API created with Gatsby Functions, I was able achieve what I desired with MDX Embed. I also had the ability to re-use that functionality and allow “Pay what You Want” functionality on my blog.
You can find out more how I made that happen here: How to Monetize Open Source Software with Gatsby Functions and Stripe
It’s at this point that using Gatsby Functions can act as a kind of Back end for front end or BFF and developing in this way is more akin to developing an API (Application Programming Interface).
APIs can be used by front-end codes to manage logins, data fetching and secure tasks not suitable for the browser. This tutorial will show you how to create an API with Gatsby Functions, and then deploy it to Gatsby Cloud.
More after jump! Continue reading below |
Preflight Checks
Gatsby Functions work when deployed to Gatsby Cloud or Netlify, and in this tutorial, I’ll be explaining how to deploy to Gatsby Cloud so you’ll need to sign up and create a free account first.
You’re also going to need either a GitHub, GitLab or BitBucket account, this is how Gatsby Cloud reads your code and then builds your “site”, or in this case, API.
For the purpose of this tutorial I will be using GitHub. You can find the final demo API code on my GitHub.
Getting Started
Create a new dir somewhere on your local drive and run the following in your terminal. This will set up a default package.json.
npm init -y
Dependencies
Type this into your terminal in order to install required dependencies.
npm install gatsby react react-dom
Pages
It’s likely your API won’t have any “pages” but to avoid seeing Gatsby’s default missing page warning when you visit the root URL in the browser, add the following to both src/pages/index.js and src/pages/404.js.
//src/pages/index.js & src/pages/404.js
export default => null;
API
Add the following to src/api/my-first-function.js.
I’ll explain a little later what 'Access-Control-Allow-Origin', '*' means, but in short, it makes sure that your APIs from other origins aren’t blocked by CORS.
//src/api/my-first-function.js
export default function handler(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.status(200).json({ message: 'A ok!' );|res.status57).json ( message: 'A ok!');|res.status (23).json( message: ‘A ok!’);|res.status = 46).json|res.status71);}
}
Scripts
Add the following to package.json.
//package.json
You can find more information here
{ "scripts": "Scripts":
"develop" = "gatsby development".
"Build" = "gatsby construct"
,|The following is a list of.|•|You can find it at.|"}
...
Start The Gatsby Development Server
To spin up Gatsby’s development server, type the following commands in your terminal.
npm run develop
Make A Request From The Browser
With the Gatsby’s development server running you can visit http://localhost: 8000/api/my-first-function, and since this is a simple GET request you should see the following in your browser.
{
"Message":
}
Congratulations
You’ve just developed an API using Gatsby Functions.
Deploy
If you are seeing the above response in your browser it’s safe to assume your function is working correctly locally, in the following steps I’ll explain how to deploy your API to Gatsby Cloud and access it using an HTTP request from CodeSandbox.
Push Code To Git
Before attempting to deploy to Gatsby Cloud you’ll need to have pushed your code to your Git provider of choice.
Gatsby Cloud
Log in to your GatsbyCloud account. Look for the purple button that reads “Add site +”.
In the next step, you’ll be asked to either Import from a Git repository or Start from a Template, select Import from Git Repository and hit next.
As mentioned, Gatsby Cloud is able to connect to GitHub or GitLab. Select your preferred Git provider and hit next.
With your Git provider connected you can search your repository and give your site name.
Once you’ve selected your repository and named your site hit next.
We won’t need the Setup and Integrations so you can skim these.
If everything went according to plan, you should see something like the one below.
You’ll see near the top on the left-hand side of the screen a URL that ends with gatsbyjs.io, this will be the URL for your API and any functions you create can be accessed by adding /api/name-of-function to the end of this URL.
E.g, the complete deployed version of my-first-function.js for my demo API is as follows:
Demo API: My First Function.
Testing Your API
Visiting the URL of your API is one thing but it’s not really how APIs are typically used. To test an API, you should request it from another source.
It’s here where res.setHeader('Access-Control-Allow-Origin', '*'); comes to the rescue. While it is not ideal to permit any domain (website), to access your functions at all, the majority of public functions are public. Setting the Access Control header to a value of * means any domain can access your function, without this, any domain other than the domain the API is hosted on will be blocked by CORS.
Here’s a CodeSandbox that uses my-first-function from my demo API. To test your function, you can fork it and modify the Axios request URL.
CodeSandbox: My First Function
Getting Fancier
Sending a response from your API that says message: "A ok! " isn’t exactly exciting so in the next bit I’ll show you how to query the GitHub REST API and make a personal profile card to display on your own site using the API you just created, and it’ll look a little like this.
CodeSandbox: Demo profile card
Dependencies
To use the GitHub API REST API, you will need to install @octokit/rest.
npm install @octokit/rest
Get GitHub User Raw
Add the following to src/api/get-github-user-raw.js.
// src/api/get-github-user-raw.js
Import 'Oktokit' from '@octokit/rest;
const octokit = new Octokit({
auth: process.env.OCTOKIT_PERSONAL_ACCESS_TOKEN
);|;|";||}
export default async function handler(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
{ try Try
const data = await octokit.request(`GET /users/username`, {
username: 'PaulieScanlon'
);|;|";||}
res.status(200).json({ message: 'A ok! ', user: data );|res.status...|res.status (|res.status = |res.status, data}
catch (error) Catch (error)
res.status(500).json({ message: 'Error!' );|res.status:|res.status (Message: 'Error!|res.status = |res.status}
|•|||}
}
Access Token
To communicate with the GitHub API REST API, you will need an access token. This access token can be obtained by following these steps from GitHub: Creating a Personal Access Token.
.env Variables
To keep your access token secure add the following to .env.development and .env.production.
OCTOKIT_PERSONAL_ACCESS_TOKEN=123YourAccessTokenABC
You can find out more information about Gatsby’s environment variables in the Gatsby Guide: Environment Variables.
Start Development Server
Just like before, type the following commands in your terminal.
npm run develop
Make A Request From The Browser
With the Gatsby development server running you can visit http://localhost: 8000/api/get-github-user-raw, and since this too is a simple GET request you should see the following in your browser. (I’ve removed part of the response for brevity. )
{
"message: A ok!" "
{ "user": "User" is the correct term.
"login": "PaulieScanlon",
"id": 1465706,
"node_id": "MDQ6VXNlcjE0NjU3MDY=",
"avatar_url": "https://avatars.githubusercontent.com/u/1465706?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/PaulieScanlon",
"type" = "User",
Site_admin: False
"name": "Paul Scanlon",
"company": "Paulie Scanlon Ltd.",
"blog": "https://www.paulie.dev",
"location" = "Worthing".
"email": "pauliescanlon@gmail.com",
True, "hireable".
"bio": Jamstack Developer/Technical Content Writer (freelance).
"twitter_username:" "pauliescanlon"
"created_at": "2012-02-23T13: 43: 26Z",
"two_factor_authentication": true,
You can find more information here
|•|||}
}
Here’s a CodeSandbox example of the full raw response.
CodeSandbox: Raw Response
You’ll see from the above that there’s quite a lot of data returned that I don’t really need, this next bit is completely up to you as it’s your API but I have found it helpful to manipulate the GitHub API response a little bit before sending it back to my frontend code.
If you’d like to do the same you could create a new function and add the following to src/api/get-github-user.js.
// src/api/get-github-user.js
Import Oktokit from @octokit/rest;
const octokit = new Octokit({
auth: process.env.OCTOKIT_PERSONAL_ACCESS_TOKEN
);|;|";||}
export default async function handler(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
{ try Try
const data = await octokit.request(`GET /users/username`, {
username: 'PaulieScanlon'
);|;|";||}
res.status(200).json({
message: "A ok!" message: 'A ok!
{ user: User
Name: Data.name
Blog_url: Data.blog
bio.data.bio
Photo: Data.avatar_url
{ githubUsername: `@$data.login`,|githubUsername `@${data.login|githubUsername `@${data.login|githubUsername `@${data.login|githubUsername `@$data.login
githubUrl data.html_url
twitterUsername: `@$data.twitter_username`,
twitterUrl: `https://twitter.com/$data.twitter_username`
|•|||}
);|;|";||}
catch (error) Catch (Error)
res.status(500).json({ message: 'Error!' );|res.status|res.status (|res.status = |res.statusto:}
|•|||}
}
You’ll see from the above that rather than returning the complete data object returned by the GitHub REST API I pick out just the bits I need, rename them and add a few bits before the username and URL values. It makes it a lot easier to create the frontend code and render the data.
Here’s a CodeSandbox example of the formatted response.
CodeSandbox: Formatted Response
This is identical to the Profile Card CodeSandbox, however I have also printed out the data so that you can clearly see the use of each manipulated data item.
It’s important to note that none of the CodeSandbox demonstrations are created using Gatsby Cloud or built with Gatsby API.
.env Variables In Gatsby Cloud
Before you deploy your two new functions you’ll need to add the GitHub Access token to the environment variables section in Gatsby Cloud.
Where To Go From Here?
This is the question I asked. Serverless functions are typically used in client-side request and while that is fine, I was curious if they could be used at build time instead of JavaScript which might or may not have been disabled by the browser.
… So that’s what I did.
Here’s a kind of data dashboard that uses data returned by Gatsby Functions at both run and build time. This site was built using Astro, and it has been deployed to GitHub Pages.
This is why I believe this is an excellent approach. I can re-use same functionality in both the browser and on the server without having to duplicate anything.
In this Astro build, I reached the same API endpoint to return data. This data is either embedded in the page (great SEO), or it’s fetched by the browser at run-time (great to show fresh and up-to-the minute data).
Data Dashboard
The data on the left side of the website is requested during build and then baked into the page using Astro. Data on the right side of the page are requested during build time using client-side requests. To query various GitHub accounts that create different lists, I used slightly different endpoints from the GitHub RESTAPI.
Everything you see on this site is provided by my more complete API. It’s called Paulie API, and it is used for many of my websites.
Paulie API
Paulie API like the API from this tutorial is built with Gatsby but because Gatsby can act as both a site and an API I’ve used it to document how all my functions work and each endpoint has its own page that can be used as an interactive playground… feel free to have a look around.
There you go, the Gatsby Functions API. It can be used from any server-side or client-side code on any site built using any technology stack.
I’d love to hear what you create. You can share your thoughts in the comments or find me on Twitter at @PaulieScanlon.
(vf, yk, il)

