Basic node.js api call without SDK

Hello. I’m using node.js to make an api call to the customers api. The block below the error response is from my server file. I’m not sure what I’m doing wrong. This is the response I’m getting.

{
  errors: [
    {
      category: 'INVALID_REQUEST_ERROR',
      code: 'NOT_FOUND',
      detail: 'Resource not found.'
    }
  ]
}

const squareAPI = async () => {
  let data = {}
  const sandbox_token = process.env.SANDBOX_ACCESS_TOKEN
  const sandBoxBaseURL = 'https://connect.squareupsandbox.com/v2/customers'

  try {
    await fetch(`${sandBoxBaseURL}&access_token=${sandbox_token}`)
      .then(res => res.json())
      .then(res => {
        data = res
      })
  } catch(error) {
    console.log(error)
  }
  return data
}

app.get('/test', (req, res) => {
  res.send(squareAPI())
})

When running this are you in the correct directory? :slight_smile:

Yes, I am. I decided to just go with the node.js SDK because the documentation follows the SDK path. I did have another question regarding requests but I’ll ask that in another post. Thank you!

The code you provided seems mostly correct, but there’s a small issue in the URL construction and the handling of the asynchronous nature of squareAPI function. Here’s the corrected version of the code:

const express = require(‘express’);
const fetch = require(‘node-fetch’); // Make sure to install the ‘node-fetch’ package

const app = express();
const PORT = process.env.PORT || 3000;

const squareAPI = async () => {
const sandbox_token = process.env.SANDBOX_ACCESS_TOKEN;
const sandBoxBaseURL = ‘https://connect.squareupsandbox.com/v2/customers’;

try {
const response = await fetch(${sandBoxBaseURL}?access_token=${sandbox_token});
const data = await response.json();
return data;
} catch (error) {
console.log(error);
throw error;
}
};

app.get(‘/test’, async (req, res) => {
try {
const data = await squareAPI();
res.json(data);
} catch (error) {
res.status(500).json({ error: ‘An error occurred’ });
}
});

app.listen(PORT, () => {
console.log(Server is running on port ${PORT});
});

I hope this will be helpful to you.

Sabela Carson
Software Developer at YES IT Labs