Request API calls

A common use case for code actions is to make API calls to external services.

Requests

From code actions you can call external APIs using a package called request. Request is based on the popular axios package.

// GET Request
async payload => {
  const result = await request.get("https://some-external-api")

  console.info('Received data', result.data)
}
// POST Request
async payload => {
  const result = await request.post("https://some-external-api", {
    orderId: '1234'
  })

  console.info('Received result', result.data)
}

Catching errors

Best practice is to catch and handle different errors when making API calls.

async payload => {
  
  try {
    // Make a request
    const result = await request.get('MY API ENDPOINT')
    // ...

  } catch(err) {
    if (err.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.error('Failed with response', err.response.data)
    } else if (err.request) {
      // The request was made but no response was received
      console.error('Failed request', err)
    } else {
      // Something happened in setting up the request that triggered an Error
      console.error('Failed in general', err)
    }
  }
}

Read more