Consuming Other APIs in a Rails App.

ukaypromise

Engr. Promise

Posted on April 22, 2023

Consuming Other APIs in a Rails App.

Ruby on Rails is a popular web framework for building web applications and APIs. It is widely used by developers due to its ease of use, convention over configuration approach, and robust features. Rails is known for its quick development time, which makes it a go-to framework for startups and developers who want to build prototypes quickly.

Rails is also used extensively for building APIs. APIs are essential for applications that require integration with other services or applications. A well-designed API makes it easy to interact with the application or service programmatically. Rails has built-in support for building APIs, which makes it a popular choice for developers.

However, consuming other APIs in a Rails application can be challenging compared to JavaScript, React, or Node applications. The challenges are primarily due to the differences in the way these frameworks handle asynchronous requests and data processing.

JavaScript and React are known for their ability to handle asynchronous requests and data processing seamlessly. This is because JavaScript and React use client-side code to handle these requests, making it easy to build fast and responsive web applications. Node, on the other hand, is known for its ability to handle large-scale applications that require a lot of data processing.

Rails, on the other hand, is a server-side framework that relies on traditional server-side processing. This means that Rails applications need to send requests to other APIs and wait for the response before processing the data. This can slow down the application and make it less responsive.

Another challenge of consuming other APIs in Rails applications is the need to parse and transform data into the required format. Unlike JavaScript and React, which can handle JSON data easily, Rails requires more effort to parse and transform data. This is because Rails relies on Ruby's built-in parsing libraries, which may not be as efficient as JavaScript's parsing libraries.

To overcome these challenges, Rails developers can use libraries and gems that simplify the process of consuming APIs. Some popular gems for consuming APIs in Rails include HTTParty, Faraday, and RestClient. These gems provide a simple and easy-to-use interface for sending requests and processing responses.

In conclusion, while Rails is an excellent framework for building web applications and APIs, consuming other APIs in Rails applications can be challenging compared to JavaScript, React, or Node applications. However, by using the right libraries and gems, Rails developers can overcome these challenges and build fast and responsive applications that integrate seamlessly with other services and applications.

If you have never implemented an external API in your rails Application, then you are in the right place as i will be showing you just how to work with other APIs in your Rails APP.
For this tutorials, We will be working with the popular News API that i can across while learning NextJs by building a Daily News web App.

You can signup at News API and get a free API key that we will be using for this tutorial.

Create a new Rails app using the following command:

rails new news-api-app
Enter fullscreen mode Exit fullscreen mode

Go into the newly created app directory:

cd news-api-app
Enter fullscreen mode Exit fullscreen mode

Open the Gemfile and add the 'news-api' gem:

gem 'news-api'
Enter fullscreen mode Exit fullscreen mode

Run bundle install to install the new gem:

bundle install
Enter fullscreen mode Exit fullscreen mode

Create a new file named 'news_api.rb' in the 'config/initializers' directory. This file will be used to initialize the News API object:

# config/initializers/news_api.rb

NewsApi = News.new("YOUR_API_KEY")
Enter fullscreen mode Exit fullscreen mode

Replace "YOUR_API_KEY" with your actual News API key.

Create a new model named 'news_article' using the following command:

rails g model news_article title:string description:text url:string source:string published_at:datetime

Enter fullscreen mode Exit fullscreen mode

Run rails db:migrate to create the news_articles table in the database.

Edit the 'news_article.rb' file and add the following line at the top to include the NewsApi module:

require_relative '../../config/initializers/news_api'

class NewsArticle < ApplicationRecord
    def self.get_news_articles
        # Use the NewsApi class here
        NewsApi.get_news
    end
end
Enter fullscreen mode Exit fullscreen mode

Create a new controller named 'news_controller' using the following command:

rails g controller news index
Enter fullscreen mode Exit fullscreen mode

This will create a controller file and a view file for the index action.

Edit the 'news_controller.rb' file and add the following code to the index action:

class NewsController < ApplicationController
  def index
    articles = NewsApi.get_top_headlines(country: 'us')
    @news_articles = articles.map do |article|
      NewsArticle.create(title: article.title, description: article.description, url: article.url, published_at: article.publishedAt)
    end
  end
end

Enter fullscreen mode Exit fullscreen mode

This code fetches the top headlines for the country 'us' using the News API, creates a new news article object for each article, and stores it in the @news_articles instance variable.

Edit the 'index.html.erb' file and add the following code to display the list of news articles:

<% @news_articles.each do |article| %>
  <div>
    <h2><%= article.title %></h2>
    <p><%= article.description %></p>
    <p>Source: <%= article.source %></p>
    <p>Published at: <%= article.published_at %></p>
  </div>
<% end %>
Enter fullscreen mode Exit fullscreen mode

This code loops through the @news_articles instance variable and displays the title, description, source, and published date of each news article.

Run rails server to start the app, and navigate to http://localhost:3000/news to see the list of news articles fetched from the News API.

That's it! You now have a simple Rails app that fetches a list of news from the News API and displays them on a web page.

You can also test it out in your rails console to see just how the data looks. In your terminal, run:

rails c
Enter fullscreen mode Exit fullscreen mode

Then run this line of code:

articles = NewsApi.get_top_headlines(country: 'us')
Enter fullscreen mode Exit fullscreen mode
irb(main):017:0> articles = NewsApi.get_top_headlines(country: 'us')
=> 
[#<Everything:0x000000010b37b3b8
...
irb(main):018:0> 
Enter fullscreen mode Exit fullscreen mode

if you run "articles" in your rails console, you should get an array of news articles.

I hope this was helpful.
Happy Coding!!!

💖 💪 🙅 🚩
ukaypromise
Engr. Promise

Posted on April 22, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related