What is REST API and how do you retrieve data for your app or website?

0

Acronym API stands for application programming interface. a API is a set of functions that facilitates communication between two software applications. Essentially, a 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, and it is an architecture used to design client-server applications. With a Rest API, you get a representation of the requested data stored in a database. A REST API is also stateless, which means that the server does not store any data between client requests.

If you are looking for a Rest API example and a detailed explanation of how it works, keep reading.

How does a REST API work?

A REST API accesses data through Uniform Resource Identifiers (URIs), which are a string of characters identifying a specific resource. The type of URI used by a REST API is a uniform resource locator (URL).

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

  • Get (used to acquire data from a database)

  • Publish (add new data to a database)

  • Update (update data in a database)

  • Delete (delete data from a database)

If you want to use the services of one of the many REST API available on the web (instead of creating one from scratch), you will only have access to the get request verb of the REST API (via a URL). These URLs have several components, but the ones you should be aware of are the API key and query.

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

Executing a get request returns a response, which contains a status code and a body. If the request is successful, the body of your response will contain the data you want to use on your website or app.

Using a JavaScript application to retrieve data from different rest APIs

To create this simple application, you need to install two other software applications on your computer: NodeJS and npm. We wrote an article on how to install NodeJS and npm on Ubuntu, as well as another on how to do it on Windows. Check them out if you want to know more.

Once the above applications are installed on your computer, you will need to perform 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 is an npm module that will play a key role in the functionality of this app. 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 [email protected]

You can now create your application.

Use the Got library to build your app

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

//fetch data from a specific REST 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 above app will retrieve data from any REST API on the Web. However, you will first need to provide the URL of the relevant resource.

Entering data from a weather REST API

The Weatherbit.io API is one of the most popular weather conditions REST API. Inserting the URL of this API in the simple JavaScript application above will make the application operational.

Using the Weatherbit.io REST API

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

//fetch data from a specific REST 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);
}
})();

Weatherbit.io URL API is now successfully inserted into the application. However, there is one aspect of the URL that you need to adjust to make the app work. This is the section called “API_KEY”, and this key is what you will receive from Weatherbit.io when you sign up for a free account.

You also have the option to adjust the query section in the code above. The app is currently polling the weather at latitude 40.7128 and longitude -74.0060, but you can insert new coordinates. Although the above query is the recommended approach, you can search for the weather in a location using the city name.

For more information on using Weatherbit.io REST API, Click here.

After inserting your API in the appropriate section above, you can now run your JavaScript file. The app will provide something similar to the following output in your terminal.

Sample Weatherbit.io REST API Response

data: [
{
rh: 53,
pod: 'd',
lon: -74.01,
pres: 1005.9,
timezone: 'America/New_York',
ob_time: '2021-09-27 14:50',
country_code: 'US',
clouds: 25,
ts: 1632754200,
solar_rad: 652.8,
state_code: 'NY',
city_name: 'New York City',
wind_spd: 5.66,
wind_cdir_full: 'west-southwest',
wind_cdir: 'WSW',
slp: 1015.9,
vis: 5,
h_angle: -30,
sunset: '22:44',
dni: 851.72,
dewpt: 12,
snow: 0,
uv: 5.68859,
precip: 0,
wind_dir: 240,
sunrise: '10:49',
ghi: 657.55,
dhi: 106.79,
aqi: 53,
lat: 40.71,
weather: [Object],
datetime: '2021-09-27:14',
temp: 22,
station: 'KJRB',
elev_angle: 40.89,
app_temp: 21.7
}
],
count: 1
}

Some of the most important aspects of the data returned in the response include:

  • City Name (returns the name of the city at the given longitude and latitude).
  • Date hour (returns the current cycle time in YYYY-MM-DD: HH format).
  • Time (returns an object containing a weather icon, a weather code and a textual description of the weather).

Entering data from a News REST API

The news API used in this section is Newsdata.io. Like everything REST API on the web, it provides several query options, which you can use to retrieve the latest news from around the world. With Newsdata.io API, you can get news from a specific country, or in a particular language, category, etc.

Using JavaScript app, you can retrieve news data REST API. Simply replace the URL in the above app 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 above URL with the API key that you will receive after registering on Newsdata.io. The above URL will return the latest news from America. However, if you want news from Japan, you can just replace the query “country = us” with “country = jp”.

For more information on using Newsdata.io REST API, Click here.

Related: Want to Add News Headlines to Your Website or App? You need the Mediastack API

Sample Newsdata.io REST API response

{
title: 'Driver Killed By His Own Car Door While Waiting In Line At Fast-Food Drive-Thru, Providing Cautionary Insights For AI Self-Driving Cars',
link: 'https://www.forbes.com/sites/lanceeliot/2021/09/27/driver-killed-by-his-own-car-door-while-waiting-in-line-at-fast-food-drive-thru-providing-cautionary-insights-for-ai-self-driving-cars/',
keywords: [Array],
creator: [Array],
video_URL: null,
description: "Sad news story about a driver that was killed by his own car door (while in a drive-thru), provides cautionary insights about
the advent of AI-based self-driving cars. Here's the insider look.",
content: "Sad news story about a driver that was killed by his own car door (while in a drive-thru), provides cautionary insights about the
advent of AI-based self-driving cars. Here's the insider look.",
pubDate: '2021-09-27 15:30:00',
image_URL: 'https://thumbor.forbes.com/thumbor/fit-in/0x0/filters%3Aformat%28jpg%29/https://specials-images.forbesimg.com/imageserve/614272b9f18bec6882652695/0x0.jpg?cropX1=23&cropX2=2455&cropY1=23&cropY2=1538',
source_id: 'forbes'
}

Using a Python app to retrieve data from different rest APIs

It is possible to recover 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 get the same results with a Python application.

Related: How to Build APIs in Python: Popular Frameworks

All you need to do is install the HTTP requests 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])

As with the previous examples, you will need to insert your API key in the appropriate section. You will then receive the same data as that returned by the JavaScript application.

Entering data for your website or app is pretty straightforward

Now you have the tools you need to recover data from your software applications. It is important to remember that the REST the architecture facilitates loose coupling, which means you can use any programming language to retrieve data from any REST API on the Web.

You now know how to use Rest API, Why not try it?


white-code-flowing-on-dark-background[1]
Web Scraping vs API: What’s the Best Way to Extract Data?

There’s data everywhere, but getting your hands on it is another problem, even if it’s legal.

Read more


About the Author


Source link

Leave A Reply

Your email address will not be published.