DEV Community

Cover image for My first Serverless service

My first Serverless service

amaralani profile image Amir Maralani ・2 min read

Recently I was going to run a service on Fandogh Paas with a custom domain and ended up using Cloudflare. When setting up stuff something caught my eye: Workers. I knew about the concept of Serverless a little but due to the circumstances using AWS is somewhat out of reach for me, so why not use this instead?!

I tried to create something with it. But the big question was what to build. Last year I created a little Discord bot to retrieve the current AQI of the provided city but since we are not using Discord anymore it's obsolete. Let's do it serverless this time!

The idea of using serverless to just call another API and pass the response on looks a bit redundant, but I guess it's good enough for learning new stuff. So I got an API token from Air Quality Open Data Platform and started coding.

There's a fair amount of documents and examples on the Cloudflare Workers site, and of course, you will need enough JavaScript knowledge.

Here's my code :

const aqiInfoUrl = ""

addEventListener('fetch', event => {

 * Respond to the request
 * @param {Request} request
async function handleRequest(request) {
  const queryString = request.url.split('?');
  let city = queryString[1].split('=')[1];

  let response = await getAQIFromAPI(city);
  return new Response(, {status: 200});

async function getAQIFromAPI(city) {
  let fullUrl = aqiInfoUrl + city + '/?token='+ API_TOKEN;
  const response = await fetch(fullUrl);
  return await response.json();
Enter fullscreen mode Exit fullscreen mode

What it basically does is that when called, tries to find the city from the query string and sends a request to "" with the provided city and the token which is saved as an environment variable.

It is not the best way it could be written, but I'm very new to this! Please give me your suggestions in the comment section.

PS: I'm thinking about a Telegram bot using the KV store ... Maybe the next post!

Discussion (0)

Editor guide