External API Calls with Fetch
In FaasPlus, you can make remote API calls directly from your functions using
fetch
, a Node.js
feature that allows you to send HTTP requests to external servers. This is useful
for integrating third-party
services, retrieving data, or posting data to other applications or APIs.
Example 1: Making GET calls
In this example, we’ll use a public service, https://api.ipify.org/, to retrieve the IP address.
const handleRequest = async (fetch) => {
const res = await fetch('https://api.ipify.org/?format=json');
const jsonRes = await res.json();
return jsonRes;
};
{
"ip": "Host external IP address"
}
Example 2: Getting All European Countries’ Locations
In this example, we’ll retrieve data on all European countries using the restcountries.com API. The function will map two properties (country name and latitude/longitude) into a new array and return it.
const handleRequest = async (fetch) => {
// Retrieve all European countries
const res = await fetch('https://restcountries.com/v3.1/region/europe');
const countries = await res.json();
const locations = countries.map(c => ({
CountryName: c.name.common,
LatLng: c.latlng
}));
return locations;
};
[
{
"CountryName": "Norway",
"LatLng": [62.0, 10.0]
},
...
]
Example 3: POST an object
In this example, we’ll use a public service, https://restful-api.dev/, to post data.
const handleRequest = async (req,fetch) => {
const postData=req.body.payload;
const res = await fetch('https://api.restful-api.dev/objects',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
});
const jsonRes = await res.json();
return jsonRes;
};
{
"payload": {
"name": "Apple MacBook Pro 16",
"data": {
"year": 2019,
"price": 1849.99,
"CPU model": "Intel Core i9",
"Hard disk size": "1 TB"
}
}
}
{
"createdAt": "2024-11-22T07:00:56.350+00:00",
"data": {
"CPU model": "Intel Core i9",
"Hard disk size": "1 TB",
"price": 1849.99,
"year": 2019
},
"id": "ff808181932badb6019352ac7d9e672d",
"name": "Apple MacBook Pro 16"
}