Making API Calls with JavaScript

Making API Calls with JavaScript

API (Application Programming Interface), as its meaning suggests, are the software interfaces of applications. In other words, we call API the code infrastructure required to use the infrastructure of an existing application to provide additional functionality to that application or to derive other applications that use that application?



When is it needed?


If we had to write every application we made throughout our lives, from top to bottom, it would be an incredible waste of time. In some cases this wouldn't even be possible. For example, while it could take years to write an artificial intelligence bot from scratch that talks to customers on our site and explains our products, with the chatgpt infrastructure, this process would not take more than a few days.


Of course, not every API infrastructure may be as salty as chatgpt. There are countless API infrastructures that are completely free or free to use at amateur level and that we can use in our software. Today we will examine how to establish a basic API connection preliminary preparation phase


First of all, since each API infrastructure has its own codes, calling techniques and result information, the first thing we need to achieve is an explanatory documentation. In this example, since I was working on region-specific weather, I made a miserly search for "free weather api without membership" to see if there was a system that I could use directly without membership.



Bingo! https://open-meteo.com/ is exactly what we are looking for. Open-Meteo, like every good service provider, has released a ready-made API interface specific to TypeScript to facilitate API operations, but today, for a more general lesson, we will continue with general requests instead of using ready-made APIs. Because in this way, we will not be able to limit ourselves to OpenMeteo and will be able to request any API.



API Request Type

API requests may work with different http infrastructures such as GET, POST, PUT etc. The most used of these are GET and POST. The main difference between the two is in how we send our variables to the API. GET will already sound very familiar to you. The URL you know is encoded text. When we enter any site, the URL written as http://sitem.com/blog?id=15 is actually a GET type request we make to the webserver. In this request type, to the web base url address? We send requests in the format change_name=change_value1i&change_name2=change_value2 after the icon.


POST, on the other hand, is a form of communication in which data is sent as an extra, listed in fields such as JSON or FormData. We will examine both of them in this article.



Open-Meteo GET Request


When I examined the Open-Meteo document, I saw that it had a very direct infrastructure. We simply send longitude, latitude location information to the API address and ask the server for the weather information we want. You can access location information from Google Maps. For example, I entered the latitude and longitude of Samsun Atakum in the URL address below.



https://api.open-meteo.com/v1/forecast?latitude=41.33&longitude=36.27&current=temperature_2m,wind_speed_10m,weather_code


In the above url address, I entered temperature_2m,wind_speed_10m,weather_code data into the current variable. According to the API documentation, with this request I want values of the current state of the weather. temperature_2m will give me the temperature of the air at 2 meters above the ground, wind_speed_10m will give me the wind speed at 10 meters above the ground, and weather_code will return the numerical indicator of the general weather condition.


Since this is a GET API, you can view the results in your browser by simply clicking on the link. The returned data is as follows;


{
  "latitude": 41.3125,
  "longitude": 36.3125,
  "generationtime_ms": 0.034928321838378906,
  "utc_offset_seconds": 0,
  "timezone": "GMT",
  "timezone_abbreviation": "GMT",
  "elevation": 15,
  "current_units": {
    "time": "iso8601",
    "interval": "seconds",
    "temperature_2m": "°C",
    "wind_speed_10m": "km/h",
    "weather_code": "wmo code"
  },
  "current": {
    "time": "2023-11-16T16:00",
    "interval": 900,
    "temperature_2m": 13.7,
    "wind_speed_10m": 9.2,
    "weather_code": 61
  }
}



In JSON data, in addition to some information about our location such as time, altitude, etc., there is current data and current_units data that will be useful to us. The Units section contains the units. For example, the temperature is 13.7 and its unit is Celsius. The only data that is incapable of human reading here is the weather_code data. It returned us a value like 61. When I examine the documentation, I see that each code represents its own unique atmosphere.


This is the list of weather conditions defined by weather codes. I think we can start working now.



GET API Request


First, let's start by creating a URL address according to the location we want.


const params = {
    "latitude": 41.33,
    "longitude": 36.27,
};


Let the params variable hold our latitude and longitude information, which we can easily change, and let's start coding with our fetch function that will make our API request.


In the callApi function, in addition to the url base, we created a url according to the latitude and longitude parameters we defined in the params object. There are many ways to translate these parameters into a GET request. Above, I simply stacked all my variables into a FormData object and then converted them into encoded URL addresses with the URLSearchParams object and combined them with my base.



The reason why I proceed this way is because we will use the FormData object in POST class data, and I think it would be beneficial for you to familiarize yourself with it. We can do it differently if we wish. For example;



let url = `https://api.open-meteo.com/v1/forecast?latitude=${params.latitude}&longitude=${params.longitude}&current=temperature_2m,wind_speed_10m,weather_code`

You can achieve the same result simply within a string as above.



While you notice, in the console.log section, I'm calling a function that I haven't written yet. I will use a simple function to convert the returned weather_code number into text. I can write this function as follows, in the light of the function I obtained from the API document;


const weatherCode = (code) => {
    switch(code) {
        default:
            return "Blue Sky";
        case 1 || 2 || 3:
            return "Partly Cloudy"case 45 || 48:
            return "Foggy"case 51 || 53 || 55 || 56 || 57:
            return "Dripping"case 61 || 63 || 65 || 66 || 67:
            return "Rainy"case 71 || 73 || 75 || 77 || 85 || 86:
            return "Profitable"case 80 || 81 || 82:
            return "Heavy Rain"case 95 || 96 || 99:
            return "Storm"
    }
}


Since all our sections are ready, let's combine the codes as follows.


const params = {
    "latitude": 41.33,
    "longitude": 36.27,
};

const callApi = async() => {
    let url = `https://api.open-meteo.com/v1/forecast?`let fd = new FormData()
    fd.append("latitude",(params.latitude).toString())
    fd.append("longitude",(params.longitude).toString())
    fd.append("current","temperature_2m,wind_speed_10m,weather_code")

    const sp = new URLSearchParams(fd)
    url += sp.toString()

    console.log(`Calling API via ${url}...`)
    let res = await fetch(url,{
        method:"GET",
    })
    let weather = await res.json()
    console.log(`Weather: ${weatherCode(weather.current.weather_code)} (${weather.current.weather_code})`)
    console.log(`Temperature: ${weather.current.temperature_2m} ${weather.current_units.temperature_2m}`)
    console.log(`Wind speed: ${weather.current.wind_speed_10m} ${weather.current_units.wind_speed_10m}`)
    return weather
}

const weatherCode = (code) => {
    switch(code) {
        default:
            return "Blue Sky";
        case 1 || 2 || 3:
            return "Partly Cloudy"case 45 || 48:
            return "Foggy"case 51 || 53 || 55 || 56 || 57:
            return "Dripping"case 61 || 63 || 65 || 66 || 67:
            return "Rainy"case 71 || 73 || 75 || 77 || 85 || 86:
            return "Profitable"case 80 || 81 || 82:
            return "Heavy Rain"case 95 || 96 || 99:
            return "Storm"
    }
}
callApi()



When I call the test.js file I saved as node test.js, I get the following result


ozcan@ostation:~/Documents/Lessons/API_CALLS$ node test.js
The API is called via https://api.open-meteo.com/v1/forecast?latitude=41.33&longitude=36.27&current=temperature_2m%2Cwind_speed_10m%2Cweather_code...
Weather: Rainy (61)
Temperature: 13.6 °C
Wind speed: 7.4 km/h



Result: Successful! I can retrieve and interpret API information as I wish.



POST API request

But what if the same API accepted only request of type POST? Then we would just need to change our code a little.


const callApi = async() => {
    let url = `https://api.open-meteo.com/v1/forecast`let fd = new FormData()
    fd.append("latitude",(params.latitude).toString())
    fd.append("longitude",(params.longitude).toString())
    fd.append("current","temperature_2m,wind_speed_10m,weather_code")

    console.log(`Calling API via ${url}...`)
    let res = await fetch(url,{
        method:"POST",
        body:fd
      })
      let weather = await res.json()
      console.log(`Weather: ${weatherCode(weather.current.weather_code)} (${weather.current.weather_code})`)
      console.log(`Temperature: ${weather.current.temperature_2m} ${weather.current_units.temperature_2m}`)
      console.log(`Wind speed: ${weather.current.wind_speed_10m} ${weather.current_units.wind_speed_10m}`)
      return weather
  }


The modified function above makes a POST request to the same data. I only made a few adjustments.

First of all, the ? at the end of the URL address. I started by removing it. Because in POST type, there is no need for such url coding. Just the base url is enough.

I then proceeded to fetch directly without changing the URL address at all. I changed the method section of Fetch from GET to POST and added a body field and assigned it to my fd variable.