INTERNET

What Is REST API and How Can You Grab Data for Your App or Website?

0

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 means representational state transfer, and it’s 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.

If you're looking for a Rest API example and an in-depth explanation of how it works, keep reading.

How Does a REST API Work?

A REST API accesses data through uniform resource identifiers (URIs), which is a string of characters that identify 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 request verbs:

  • Get (this is used to acquire data from a database)
  • Post (add new data to a database)
  • Put (update the data in a database)
  • Delete(delete data from a database)

If you want to utilize 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, which contains a status code and a body. If the request is successful, your response body will contain the data you want to use on your website or application.

Using a JavaScript Application to Grab Data From Different Rest APIs

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

After the applications above are installed on your computer, 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 applicationconst 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 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 REST 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 applicationconst 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);}})();

The URL for the Weatherbit.io API is now successfully inserted into 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”, and this 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.

For more information on how to use the Weatherbit.io REST API, click here.

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

Weatherbit.io REST API Response Example

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 more important aspects of the data returned in the response include:

  • City_name (returns the name of the city at the longitude and latitude provided).
  • Datetime (returns the current cycle hour in the YYYY-MM-DD: HH format).
  • Weather (returns an object containing a weather icon, weather code, and a text description of the weather).

Grabbing Data From A News REST API

The news API used in this section is Newsdata.io. 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 “contry=us” query with “country=jp”.

For more information on how to use the Newsdata.io REST API, click here.

Newsdata.io REST API Response Example

{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 aboutthe 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 theadvent 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 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.

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 libraryimport requests# grabbing data using the requests libraryURL = '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])

Similar to the previous examples, you’ll need to insert your API key in the relevant section. You’ll then receive the same data that the JavaScript application returns.

Grabbing Data for Your Website Or Application Is Pretty Simple

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

Now you know how to use Rest API, why not give it a try?

admin

Surfshark Names the Websites Tracking Your Every Move (and Those That Aren’t)

Previous article

How to Reset a WordPress Website

Next article

You may also like

Comments

Leave a reply

Your email address will not be published. Required fields are marked *

More in INTERNET

Login/Sign up