Skip to main content Link Search Menu Expand Document (external link)

Web API

Web API is an API that can be accessed over the web using the HTTP Protocol. We use Web API to provide services by transferring information between our web server to different kinds of devices like laptop, mobile, and others.

What is an API?

API is the acronym for Application Programming Interface, a piece of code that sends instructions or data to another application.

For example, let’s say we want to create a web application that displays the latest news. We can look for an API that provides the information and save the records in our database. Then we could also build our API to let other applications get data from us.

Nowadays, there is a lot of free information on the internet that you can retrieve and use, but free APIs requests are generally limited. We can connect to those Web API services to help us add data to our applications.

Web API service

In this lesson, our goal is to retrieve data from a Web API service. There are a lot of free Web API services that we can choose.

https://newsapi.org/s/philippines-news-api/

Today we’ll be using a News API. It’s a simple HTTP REST API for searching and retrieving live articles from the world wide web.

Before we can start retrieving data from this Web service we need to register and get our API key.

Go to this url https://newsapi.org/register.

Fill out the form and submit You will be redirected to https://newsapi.org/account. In this page you can find your API key.

Rest Client

Rest Client is one of the popular gems. We use this gem to create an HTTP request. It is inspired by Sinatra’s microframework style of specifying actions: get, put, post, delete.

Now that we already have our API key. Go to our project and install this gem.

How to install Rest Client

Reminder:

Make sure that your containers are up and running.

In your Gemfile, add the rest-client gem.

gem 'rest-client'

Then run bundle install.

 $~/KodaCamp> docker-compose exec app bash
 root@0122:/usr/src/app# install
  root@908c63835a38:/usr/src/app# bundle install
  # ...
  Installing unf_ext 0.0.8.2 with native extensions
  Fetching mime-types 3.4.1
  Installing mime-types 3.4.1
  Fetching unf 0.1.4
  Installing unf 0.1.4
  Fetching domain_name 0.5.20190701
  Installing domain_name 0.5.20190701
  Fetching http-cookie 1.0.5
  Installing http-cookie 1.0.5
  Fetching rest-client 2.1.0
  Installing rest-client 2.1.0
  Bundle complete! 14 Gemfile dependencies, 70 gems now installed.
  Use `bundle info [gemname]` to see where a bundled gem is installed.

Open your irb console.

 root@0122:/usr/src/app# rails c
  Loading development environment (Rails 7.0.4)
  irb(main):001:0>

This endpoint provides live top and breaking headlines for a country-specific category in a country, single source, or multiple sources. You can also search with keywords. Articles are sorted by the earliest date published first.

https://newsapi.org/v2/top-headlines

This endpoint is great for retrieving headlines for use with news tickers or similar.

Create variables to store the api_key, url, and parameters for our request.

irb(main):001:0> api_key = 'YOUR API TOKEN'
=> "YOUR API TOKEN"
irb(main):002:0> url = 'https://newsapi.org/v2/top-headlines'
=> "https://newsapi.org/v2/top-headlines"
irb(main):003:0> params = { 'apiKey': api_key, country: 'ph' }
=> {:apiKey=>"YOUR API TOKEN", :country=>"ph"}

You can check the /v2/top-headlines documentation to get more parameters that you can try.

{ 'apiKey': api_key, country: 'ph' }

Send our request with the RestClient class

irb(main):001:0> response = RestClient.get url, params: params
=> <RestClient::Response 200 "{\"status\":\"...">
irb(main):006:0> response.body
=> # returns the body of the response

JSON

The response.body from our request is a string because it responded in JSON format. Most of the Web APIs usually returns data in JSON or XML formats. These two are the most common data formats. JSON is a string with key-value pairs and XML is a markup language and it compose of tags similar HTML. Both JSON and XML can be used to receive data from a web server.

The data that we got from our request is a JSON.

It similar to this string.

"{\"id\":1,\"title\":\"My first blog\",\"content\":\"My first content\"}"

Because JSON is a string, we can convert or parse it into a usable object. Different programming languages can generate and parse this JSON string. We can use JSON.parse to convert JSON to a ruby object. In Ruby, after parsing JSON, we can use it as a hash.

irb(main):001:0> json_data = "{\"id\":1,\"title\":\"My first blog\",\"content\":\"My first content\"}"
=> "{\"id\":1,\"title\":\"My first blog\",\"content\":\"My first content\"}"         
irb(main):002:0> converted_data = JSON.parse(json_data)
=> {"id"=>1, "title"=>"My first blog", "content"=>"My first content"}                                                   
irb(main):003:0> converted_data.keys
=> ["id", "title", "content"]                     
irb(main):004:0> converted_data.values
=> [1, "My first blog", "My first content"]                       
irb(main):005:0> converted_data['id']
=> 1
irb(main):006:0> converted_data['title']
=> "My first blog"
irb(main):007:0> converted_data['content']
=> "My first content"

We could also generate our JSON by using the to_json method. It converts our Ruby hash to JSON.

irb(main):001:0> { id: 1, title: "My first blog", content: "My first content" }.to_json
=> "{\"id\":1,\"title\":\"My first blog\",\"content\":\"My first content\"}"

Now, let’s parse the response from our request.

irb(main):001:0> response_body = JSON.parse(response)
=> 
{"status"=>"ok",
...
irb(main):006:0> response_body.keys
=> ["status", "totalResults", "articles"]  
irb(main):007:0> response_body['articles'][0]
=> # returns the first article it can found

If you have questions about the gem, you can check the rest client documentation.


Back to top

Copyright © 2020-2022 Secure Smarter Service, Inc. This site is powered by KodaCamp.