Ibrahim Abdullahi's Blog

Ibrahim Abdullahi's Blog

What is an API for a beginner with an example.

Some years ago while I was trying to learn "What an API is", I come across many tutorials talking about interfaces and coffee shops which confuses me even more. So today, I will try to explain to you what I understand by API, and later we'll see an example of how to work with an API. So API (which stands for Application Programming Interface) can simply be referred to someone's code that you want to use in your application/website, without worrying how the code is written(that what the 'i' in the API means). Say we wanted to design a software that displays weather information based on the location a user searches(this is what we will be building later), but instead of writing our own code that will fetch the information from NASA's NOAA weather satellite or some stations, we will use an API from someone that already done that. The API which usually comes in the form of URL can be accessed by sending a request to the API and in response, the API will give us back information that we can use.

Some API Keywords

  1. API URL: This is the base URL we are sending the request to can be both get or post request.
  2. API Key: Some API contains some confidential information as such there is a need for authentication before accessing it, while some are paid services.
  3. API Endpoint: Some API URL has many different resources to access, the endpoints differentiate what the API responds with.
  4. API Queries: These are the piece of data that you attached during your API request.

API Example:

As mentioned above, we are going to create a web application that will make an API request for weather information. The API will be gotten from Open Weather Map, after requesting the API, we will receive a response in JSON form and then we can use data return and display it the application. To save time, I'm not going to explain all the markup and the styling, but if you want the explanation, you can watch this youtube, the only difference is that the video was done with Vuejs. %[youtube.com/watch?v=JLc-hWsPTUY] We will be working with 3 files index.html, script.js, and style.css.

Markup:

our index.html will contain the following code: %[gist.github.com/Aybee5/0467295f8e74563521e3..

Style:

Our style.css will contain the following code: %[gist.github.com/Aybee5/771dda61e452f8bb9564..

###Script: Finally, our script.js will contain the following code: %[gist.github.com/Aybee5/a739e0f293f389fd0ef1.. Here we declare some variables and get the element of the ids that we will later fill in with the response we will get back, and a function that checks for Enter key event to make the API call. So the next thing to do is go to Open Weather Map and sign up to generate an API key and use the API. After getting the API key, we will then replace the empty api_key variable with the one we generate, my API Key is '3a2905bb552cfde3a564bd0548d594a9'. The API URL is https://api.openweathermap.org/data/2.5/, so replace the empty api_url with that. Tada :tada: we are done with creating our UI it's now time to make our API request. For the API request, we are going to make use of Fetch API(Yes, this is another. We make use of different APIs every day) to make the request. We are going to write the method inside the apiFetch inside the if block.

function apiFetch(event) {
  if (event.key === "Enter") {
    // make API request
    fetch(`${base_url}weather?q=${searchKey.value}&units=metric&APPID=${api_key}`)
      .then(response => {
        return response.json();
      })
    }
}

We call the fetch() with an API endpoint /weather and with the following API queries: i. q=${searchKey.value}: which is the value of what the user input in the search box. ii. units=metric: which is the unit we want to retrieve back our weather value, you can learn more on the weather Map website. iii. APPID=${api_key} which is our API key We then wait for a response and when we got the response, we convert it to JSON. Here is a sample of our JSON json response Finally, we are going to do is extract the values we want from the jsonResponse and display it to the user. We should add the following to the code

.then(resJSON=>{
   countryName.innerHTML = resJSON.name+ ', '
   countryCode.innerHTML = resJSON.sys.country
   temp.innerHTML = Math.floor(resJSON.main.temp) + '°c'
   weather.innerHTML = resJSON.weather[0].main
   if (resJSON.main.temp > 16) {
     document.getElementById('app').className = 'warm'
   }
   else {
     document.getElementById('app').className = ''
   }
 })

that last if statement is to apply a class to the app based on the data temperature. Congratulations, we've created a weather app and consume an API. You can find a list of public API to use in this repo If you like to see the source code, you can find it on GitHub at %[github github.com/Aybee5/api-tutorial]

 
Share this