An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
Google action fetching data from an API
Now that we have our action triggered programmatically let's see how we can get the response data from an API.
This way, we can make it a bit more interactive.
If you'd like to follow along, please complete the first.
Fetching API data in a google action
The cool part now that we have our action using a function is that we can use all kinds of node goodies.
One of these goodies is the fetch API.
Let's use a placeholder API first, so it's easier to test.
Open up your action and start by adding the fetch API.
const fetch = require('node-fetch');
Then inside our greeting function, we should convert it to an async function.
// Previousapp.handle('greeting', (conv) => {});// Newapp.handle('greeting', async (conv) => {});
Now that our function is asynchronous, we can await the fetch; since it's direct JSON we can await the JSON conversion as well like this:
app.handle('greeting', async (conv) => { const response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const text = await response.json();});
And then, we can modify our response card to return this data instead of the static data.
app.handle('greeting', async (conv) => { const response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const text = await response.json(); conv.add( new Card({ title: text.title, text: text.body, image: new Image({ url: 'https://daily-dev-tips.com/images/logo.png', alt: 'Daily Dev Tips logo', }), }) );});
You can now save and deploy your function, be sure to wait a minute or so for it to deploy.
Then test your function and see it in action!
And that's it. We now added an API call to our Google action!
Pretty cool stuff, if I may say so.
Thank you for reading, and let's connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter
Original Link: https://dev.to/dailydevtips1/google-action-fetching-data-from-an-api-4lg7
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To