Key Takeaways

  • APIs facilitate communication between software applications by taking requests and returning relevant responses, making it easier to access and manipulate data.
  • REST APIs use URIs to access and manipulate resources, with different request verbs like GET, POST, PUT, and DELETE for fetching, adding, updating, and deleting data respectively.
  • By using libraries like got in JavaScript or requests in Python, you can build applications that grab data from various REST APIs, simply by providing the API key and query in the URL.

The acronym API stands for application programming interface. An API is a set of functions that facilitates communication between two software applications. Essentially, an API takes a request from one software application to another, then returns to the initiating software with a relevant response.

REST stands for representational state transfer, an architecture used to design client-server applications. With a REST API, you’re getting a representation of the requested data stored in a database. A REST API is also stateless, which means that the server doesn’t store any data between requests from clients.

How Does a REST API Work?

A REST API accesses data through URIs (uniform resource identifiers). URIs are strings of characters that identify a specific resource. The specific type of URI used by a REST API is usually a URL (uniform resource locator).

To access and manipulate resources, a REST API uses the following request verbs:

  • Get—fetches data from a database.
  • Post—adds new data to a database.
  • Put—updates data in a database.
  • Delete—deletes data from a database.

If you want to use the services of one of the many REST APIs available on the web (instead of building one from scratch), you’ll only have access to the get request verb of the REST API (through a URL). These URLs have several components, but the ones that you need to know are the API key and the query.

The API key is a unique identifier, which you’ll receive once you register on a REST API platform. The query is usually a simple equation used to personalize your search. Therefore, if you wanted to get the current weather in New York City, the query section of your URL might be “city=New York”.

Executing a get request returns a response that includes a status code and a body. If the request is successful, your response body will contain the data that you intend to use on your website or application.

Using a JavaScript Application to Grab Data From Different REST APIs

To build this JavaScript application, there are two software applications that you need to install on your computer: NodeJS and npm. We have an article on how to install NodeJS and npm on Ubuntu, as well as one on how to install NodeJS and npm on Windows—so check those out if you want to learn more.

After you install the applications above, you’ll need to take the following steps:

  1. Open your IDE and launch the terminal.
  2. Navigate to the folder containing your JavaScript application file using the cd command.
  3. Initialize npm with the following line of code:
            npm init -y
        

There’s one npm module that’ll play a key role in this application’s functionality. This is the got module, which is an HTTP request library for NodeJS. The following line of code will install the latest version of the got library in your application files:

        npm install got@latest
    

Now you can go ahead and build your application.

Using the Got Library to Build Your Application

        // import the got library into your application
import got from 'got';

// fetch data from an API and prints its body to the terminal
(async () => {
  try {
    const response = await got(URL);
    const data = JSON.parse(response.body);
    console.log(data);
  } catch (error) {
    console.log(error.data);
  }
})();

The application above will grab data from any REST API on the web. However, you’ll need to provide the URL for the relevant resource first.

Grabbing Data From a Weather REST API

The Weatherbit.io API is one of the more popular weather APIs. Inserting the URL of this API into the simple JavaScript application above will make the app operational.

Using the Weatherbit.io REST API

        // import the got library into your application
const got = require('got');

// fetch data from an API and prints its body to the terminal
(async () => {
  try {
    const URL =
     'https://api.weatherbit.io/v2.0/current?lat=40.7128&lon=-74.0060&key=API_KEY';

    const response = await got(URL);
    const data = JSON.parse(response.body);
    console.log(data);
  } catch (error) {
    console.log(error.data);
  }
})();

The URL for the Weatherbit.io API is now a part of the application. However, there’s one aspect of the URL that you need to adjust to get the application running. This is the section labeled “API_KEY”. The API key is what you’ll receive from Weatherbit.io when you register for a free account.

You also have the option of adjusting the query section in the code above. The application is currently querying the weather at the latitude of 40.7128 and the longitude of -74.0060, but you can insert new coordinates. Though the query above is the recommended approach, you can search for the weather at a location using the city name.

After inserting your API key in the relevant section above, you can now execute your JavaScript file. The application will show something like the following output in your terminal:

Weather API response part1
Weather API response part2

Some of the more important aspects of the response data include:

  • city_name—the name of the city at the longitude and latitude provided.
  • datetime—the current cycle hour in the YYYY-MM-DD: HH format.
  • weather—an object containing a weather icon, weather code, and a text description of the weather.

Grabbing Data From a News REST API

This section uses the Newsdata.io API. Like all REST APIs on the web, it provides several query options, which you can use to retrieve breaking news from around the world. With the Newsdata.io API, you can get news from a specific country, or in a particular language, category, and so on.

Using the JavaScript Application, you can retrieve data from the news REST API. Simply replace the URL in the application above with the following URL:

        'https://newsdata.io/api/1/news?apikey=YOUR_API_KEY&country=us'

The next step is to replace the “YOUR_API_KEY” section in the URL above with the API key that you’ll receive after you register with Newsdata.io. The URL above will return breaking news from America. However, If you want news from Japan, you can simply replace the “country=us” query with “country=jp”.

The response body will be an array of objects containing news from America. The following object is the first in the array:

News API response part1
News API response part2

Using a Python Application to Grab Data From Different Rest APIs

It’s possible to grab data for your website or application using any programming language that you are familiar with. So, if you don’t want to use JavaScript, you can achieve the same results with a Python application. You can build a Python API using one of its frameworks, or grab data from an existing REST API using a simple script.

All you need to do is install the requests HTTP python module using the pip environment. Then, you can build your Python application using the following code:

        # import the requests library
import requests

# grabbing data using the requests library
URL = 'https://newsdata.io/api/1/sources?apikey=YOUR_API_KEY=us'
res = requests.get(URL)
json = res.json()

for key in json:
    print(key, json[key])

Like the previous examples, you’ll need to insert your API key into the relevant section. You’ll then receive a response body that is similar to the one that the JavaScript application returns.

News API response (Python)

Grabbing Data for Your Website or Application Is Pretty Simple

You now have the tools you need to grab data for your applications. It’s important to remember that the REST architecture facilitates loose coupling. This means that you can use any programming language to grab data from any REST API on the web.

You should also remember that the API key and query play a vital role in your ability to access the specific data that you need for your application.