Skip to main content

Serverless Function with External API Calls

In this tutorial, we'll create a serverless function that makes external API calls. You'll learn how to set up a serverless function that interacts with external APIs.

Prerequisites​

Before proceeding with this tutorial, make sure you have:

Create a serverless function​

Let's get started by building a simple ETH price lookup function that calls an external API!

First, create a new file called eth-price.js with the following code:

addEventListener(
'fetch',
event => {
event.respondWith(handle(event.request));
});

async function handle(request) {
try {
const response = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd');
const data = await response.json();
const ethPrice = data.ethereum.usd;
return new Response(ethPrice);
} catch (err) {
console.log(err);
return new Response('Error fetching eth price');
}
}

To test the function locally, run the test server:

sudo ./mock_serverless.sh 8090 eth-price.js

Then, send a POST request to the server:

curl -X POST http://localhost:8090/

To optimize the code for deployment, you should minify it using Terser. Run the following command:

npx terser eth-price.js -m -o eth-price.min.js

Execute the serverless function​

Next, you need to provision the code. Follow the instructions in the code provision guide to complete this step.

Assume you have a transaction hash 0x6516be2032b475da2a96df1eefeb1679a8032faa434f8311a1441e92f2058fe5. Convert it to base32 encoding using the following command:

echo -n "0x6516be2032b475da2a96df1eefeb1679a8032faa434f8311a1441e92f2058fe5" | xxd -r -ps | base32 | sed 's/=*$//'

Finally, use the base32 encoded transaction hash to call the Web2 API. Execute the following command:

curl MULL4IBSWR25UKUW34PO72YWPGUAGL5KINHYGENBIQPJF4QFR7SQ.oyster.run -v

The output should look like this:

* Host MULL4IBSWR25UKUW34PO72YWPGUAGL5KINHYGENBIQPJF4QFR7SQ.oyster.run:80 was resolved.
* IPv6: (none)
* IPv4: 13.232.36.95
* Trying 13.232.36.95:80...
* Connected to MULL4IBSWR25UKUW34PO72YWPGUAGL5KINHYGENBIQPJF4QFR7SQ.oyster.run (13.232.36.95) port 80
> GET / HTTP/1.1
> Host: MULL4IBSWR25UKUW34PO72YWPGUAGL5KINHYGENBIQPJF4QFR7SQ.oyster.run
> User-Agent: curl/8.5.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: nginx/1.18.0 (Ubuntu)
< Date: Tue, 29 Oct 2024 07:23:09 GMT
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 27
< Connection: keep-alive
< x-oyster-signature: 65d73d41157b72d12a87f7550041159addb4307a0ee7ed93c93d0da43501684513c66812ecf4abc71e3bd899ec0b34a6c86bf4abbcf1a127394fca8859a015651c
< x-oyster-timestamp: 1730186589
<
* Connection #0 to host MULL4IBSWR25UKUW34PO72YWPGUAGL5KINHYGENBIQPJF4QFR7SQ.oyster.run left intact
Current ETH Price: $2609.58

Kudos! You've successfully created a serverless function that makes external API calls. Next, you'll learn how to make Web3 requests from your contracts and handle the response callbacks.