OpenWhisk Actions on Knative - Call External APIs
This is a follow up blog post of How to run OpenWhisk actions on Knative?
In this blog post, we are going to experiment with OpenWhisk action to call an external API.
The examples so far have been self-contained JavaScript functions. We can also create an action that calls an external API. This example invokes a Yahoo Weather service to get the current conditions at a specific location.
Note that this action uses the JavaScript request
library to make an HTTP request to the Yahoo Weather API, and extracts fields from the JSON result. The action returns a Promise to indicate that the result of this action is not available yet when the function returns. Instead, the result is available in the request
callback after the HTTP call completes, and is passed as an argument to the resolve()
function.
Pre-requisites:
- Secret exists on Knative, check with:
$ kubectl get secret dockerhub-user-pass
- Service Account exists on Knative, check with:
$ kubectl get serviceaccount openwhisk-runtime-builder
- Build Template exists on Knative, check with:
$ kubectl get buildtemplate openwhisk-nodejs-runtime
If any of the secret/service account/build template does not exist on your Knative installation, please go back to the How to run OpenWhisk actions on Knative? blog post and run Step 1 through Step 3 depending on what’s missing.
Deploy NodeJS Runtime with Action Code
Configure the build file to point to your Docker Hub repo by replacing DOCKER_USERNAME
with your username.
Deploy NodeJS runtime with action code:
$ kubectl apply -f build.yaml
build.build.knative.dev/nodejs-10-weather created
Verify the build pod exists:
$ kubectl get build.build.knative.dev/nodejs-10-weather
NAME SUCCEEDED REASON STARTTIME COMPLETIONTIME
nodejs-10-weather True 1m
Serve NodeJS Runtime as a Knative Service
Configure the service template to point to the Docker Hub repo where the OpenWhisk runtime (built in previous step) will be pulled from. Replace ${DOCKER_USERNAME}
and create service.yaml
:
Run Action
Depending on your Knative installation, determine how to access your knative gateway. Copy the JSON payload and run:
Note that JSON payload under
activation
is reserved for OpenWhisk controller/invoker and can be ignored.
curl -H "Host: nodejs-weather.default.example.com" -d '@weather.json' -H "Content-Type: application/json" http://<IP_ADDRESS>:<PORT>
{ "msg": "It is 28 degrees in Barcelona, Spain and Cloudy" }
Enjoy! 👍