Thursday 5 August 2021

Gatsby API Request on Build Time

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?



from Gatsby API Request on Build Time

No comments:

Post a Comment