I have a gatsby project where I need to make an API request to fetch a list of cars that I will use to dynamically create pages for each car. The API response data is like so:
{
"Fleet_Data": [
{
"Make": "Honda",
"Model": "Pilot"
},
{
"Make": "Honda",
"Model": "CRV"
},
{
"Make": "Honda",
"Model": "Accord"
}
]
}
I am using the gatsby-source-custom-api plugin. Here's my gatsby-config.js
file:
{
resolve: "gatsby-source-custom-api",
options: {
url: "https://api.fleetdata.com/",
headers: {
Authorization: 'Basic API_KEY'
},
rootKey: "Fleet_Data",
schemas: {
Fleet_Data: `
Make: String
Model: String
`
}
}
}
I don't have anything in my node file except for debugging but here's my gatsby-node.js
const path = require("path");
exports.createPages = async ({ graphql }) => {
console.log("IT WORKED")
};
But when I run gatsby build
I get the following error in the console:
"gatsby-source-custom-api" threw an error while running the sourceNodes lifecycle:
invalid json response body at https://api.fleetdata.com/ reason: Unexpected token : in JSON at position 4
23 |
24 | const URL = getUrl(process.env.NODE_ENV, url)
> 25 | const data = await fetch(URL).then(res => res.json())
| ^
26 |
27 | const typeDefs = getTypeDefs(schemas, imageKeys)
28 | createTypes(typeDefs)
File: node_modules/gatsby-source-custom-api/gatsby-node.js:25:16
FetchError: invalid json response body at https://api.fleetdata.com/ reason: Unexpected token : in JSON at position 4
- index.js:272
[ProjectCars]/[node-fetch]/lib/index.js:272:32
- task_queues.js:95 processTicksAndRejections
internal/process/task_queues.js:95:5
- gatsby-node.js:25 Object.exports.sourceNodes
[ProjectCars]/[gatsby-source-custom-api]/gatsby-node.js:25:16
- api-runner-node.js:429 runAPI
[ProjectCars]/[gatsby]/src/utils/api-runner-node.js:429:16
not finished source and transform nodes - 3.913s
What am I doing wrong here?
This was solved by a simple fetch api call in the gatsby-node.js
file instead of using the plugin. The gatsby-source-custom-api
plugin does not seem to be intended to be used for this particular case despite its name and documentation..