Calling an API from Homey Script

Hi, I want to call an API from Amber Electric (Australian electricity retailer who sells at wholesale prices) from Homey Script. I know the API works as I can test it in Ambers Github space, and get a result returned. They gave me a script to try it with but I get an error when I test it.

Here is the script:

const apiKey = 'psk_f31a4b0b3ee67b8db63067a7d0385bd0'
const siteId = '01H92N0GC70BAZHM48P2C52J3M'

const response = await fetch(`https://api.amber.com.au/v1/sites/${siteId}/prices/current`, { 
  headers: { 
    'Authorization': `Bearer ${apiKey}` 
  } 
}
const prices = await response.json()
const generalPrice = prices.find((price) => price.channelType === 'general')?.perKwh
const feedInPrice = prices.find((price) => price.channelType === 'feedIn')?.perKwh

Here is the error:
:x: Script Error
:warning: Get Current FIT.js:8
}
^

SyntaxError: missing ) after argument list
at new Script (node:vm:94:7)
at HomeyScriptApp.runScript (/app/app.js:483:23)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.runScript (/app/api.js:30:22)

Here is a copy of part of the response when calling the API:

I think it’s just like the syntax error says - the open bracket ( after fetch doesn’t have a matching close bracket?

So I think the script should read:

const apiKey = 'psk_f31a4b0b3ee67b8db63067a7d0385bd0'
const siteId = '01H92N0GC70BAZHM48P2C52J3M'

const response = await fetch(`https://api.amber.com.au/v1/sites/${siteId}/prices/current`, { 
  headers: { 
    'Authorization': `Bearer ${apiKey}` 
  } 
});
const prices = await response.json()
const generalPrice = prices.find((price) => price.channelType === 'general')?.perKwh
const feedInPrice = prices.find((price) => price.channelType === 'feedIn')?.perKwh

You then need to add something to the script to do something with the responses so you can see the output.

1 Like
const response = await fetch(`https://api.amber.com.au/v1/sites/${siteId}/prices/current`, { 
  headers: { 
    'Authorization': `Bearer ${apiKey}` 
  } 
})

is missed a “)”

Thanks. Initially I put the ) in the wrong place, but when I added ); in the place you indicated it worked.
Now, as you alluded to I get Return Undefined.
I added a log function to display generalPrice and feedInPrice and they now display.
I want to run this from a flow and put the responses into variables.
If you have some advise to share on that it would be appreciated, otherwise I will search the forum and try and work it out, then come back to you if I can’t.

Thank you all again. This community is magic.

add

return true 

and you don’t have undefined

Use log() function for debugging

log(variable_to_print)
1 Like