DZone
In a previous blog post, I showed how to create your first cloud function (plus a video). It’s very likely that your cloud function will need to invoke an external REST API. The following tutorial will show you how to create such a function (it’s very easy).
- Sign into an IBM Cloud account
- Click Catalog
- Remove the label:lite filter and type
- Click on Functions box
- Click the Start Creating button
- Click Create Action
- For Action Name, enter "ajoke" and click the Create button. A new cloud function will be created with Hello World message
- Replace the function code with the following code which invokes a 3rd party REST API which returns a random joke:
var request = require("request"); function main(params) { var options = { url: "https://api.icndb.com/jokes/random", json: true }; return new Promise(function (resolve, reject) { request(options, function (err, resp) { if (err) { console.log(err); return reject({err: err}); } return resolve({joke:resp.body.value.joke}); }); }); }
- The code is simple. It uses the request Node.js package to connect to an external REST API
- The external REST API returns a random joke
- A JavaScript Promise is used for invoking the REST API
- At the end, the cloud function returns a response in JSON format
- Now click the Save button to save the code. Once the code is saved, the button will change to Invoke. Click the button to invoke the function. In the right-hand panel you should see output with a random joke:
{ "joke": "Project managers never ask Chuck Norris for estimations... ever." }
This is how it looks inside the IBM Cloud Functions editor:
Source: DZone