4—Using Nomad to Consume a Web API
Publish and subscribe a Web API in Browser
At some point, you'll probably want to create a composite node using one or multiple REST APIs or services that you have at your disposal. We've provided an example webapi.js
file that makes an http request to openweathermap, returns data, and broadcasts it to a nomad node.
To "nomad-ify" the API, all you need to do is replace YOUR_APPID
with your openweathermap app ID (api key) in the appID
const inside of webapi.js
. If you don't have one, you can create one here super quick for purposes of the demo.
A caveat, if you're just creating your api key, it may take anywhere from 10 minutes to an hour to be fully functional, this is a limitation on the openweathermap end of things.
// API stuff
const city = 'London'
const appID = 'YOUR_APPID'
const requestUri = `http://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=${appID}`
Using the finder, right click to open web-api/webapi.html
in Chrome. Once you click the request button the page, Nomad will make a request to the openweathermap api and print the data it receives out onto the page.
Structuring your requestUri
will be different depending on the API in question. The URL you send may need to include credentials or an api key or authorization token of some sort.
Breaking it Down
Breaking down the code in the example, we're calling the request function on click of the fetch button:
// Attach handlers and http request
//////////////////////////////////////////
document.getElementById("fetch").onclick = () => {
if (!node.isOnline()) {
console.log('Nomad is not yet started')
return
}
request(requestUri)
}
The request function creates an http request and a promise for Nomad to publish the data when it receives it. Nomad then adds a new element to the page containing the data received.
const request = (url) => {
const httpRequest = new XMLHttpRequest()
const publishToNomad = () => {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
// Publish to nomad!
// Note: This is also where some parsing and working with data might take place
node.publish(httpRequest.responseText)
const printStr = `You just published: ${httpRequest.responseText}`
console.log(printStr)
window.nomadUtils.addElement(printStr)
} else {
const errStr = `There was a problem with the HTTP request: ${httpRequest.response}`
window.nomadUtils.addElement(errStr)
console.error(error)
}
}
}
if (!httpRequest) {
window.nomadUtils.addElement('Cannot create an XMLHTTP instance.')
return
}
httpRequest.onreadystatechange = publishToNomad
httpRequest.open('GET', url)
httpRequest.send()
}