DEV Community

Honeybadger Staff for Honeybadger

Posted on • Originally published at honeybadger.io

Building on Reddit's API with JavaScript

This article was originally written by
Muhammed Ali
on the Honeybadger Developer Blog.

Reddit is a news aggregation, communication, and discussion application. If you want to get more information about a particular topic or have a question, Reddit is the place to be. The data on Reddit are provided to the public through its API.

The Reddit API is beneficial if you want to integrate Reddit communications into your application or if you just want to use certain data on Reddit.

The aim of this tutorial is to show how you can extract article content from Reddit using the Reddit API. I will show how the results can be limited to the range of 5 to 100 results. We will also build a feature to sort the articles by either relevance or date (latest). Extraction of the data will be done with JavaScript, and then it will be bundled with Parcel so that we can view the data in a browser.

You can find the code used in this article on GitHub.

Prerequisites

To follow along with this tutorial, you should have the following:

  1. Basic knowledge of APIs.
  2. Basic knowledge of JavaScript.
  3. npm installed.

How to Set Up Parcel

Parcel is a JavaScript bundler for Web applications with zero configuration and is straight-forward to set up. It packages all the application files in a dist folder, so the application can be run.

To get started, we will install Parcel. First, create a new folder for the project and navigate to it on your terminal. You can now run the following command to install Parcel with npm:

npm install --save-dev parcel
Enter fullscreen mode Exit fullscreen mode

Parcel also starts the development server on the terminal, which you can do by running the following command in the terminal:

npx parcel index.html
Enter fullscreen mode Exit fullscreen mode

Building the Application

First, create index.html and index.js files in the folder you created in the previous section.

To show all the features that were mentioned in the introduction of this tutorial, we will build an app so you can see how each functionality might be used. This app is built using HTML, Bootstrap, and JavaScript.

Let’s first brush through the HTML. Since we are using bootstrap, we need to get the CDN link. We will be going straight to the JavaScript work. You can get the full HTML code from GitHub to follow along.

Developing the JavaScript Section

We have to get the ids for the search button and input form and then add an event listener so that when you submit the form, a function is triggered to get the “sortby” input value and the “limit”.

To make sure we cannot submit an empty search box, we will add an alert message. This will be done using an if statement.

You can get this working by pasting the following code into your index.js file:

const searchForm = document.getElementById("search-form");
const searchInput = document.getElementById("search-input");

// Form event listener
searchForm.addEventListener("submit", (e) => {
  e.preventDefault();
  // get search term
  const searchTerm = searchInput.value;
  //get sort
  const sortBy = document.querySelector('input[name="sortby"]:checked').value;
  // get limit
  const searchLimit = document.getElementById("limit").value;
  // check input if empty
  if (searchTerm === "") {
    showMessage("Please add a search term", "alert-danger");
  }
  // to clear input after search
  searchInput.value = "";
});
Enter fullscreen mode Exit fullscreen mode

Fetching the Reddit API

To fetch data from Reddit, we will create another JavaScript file at the root of your project named redditapi.js. In this file, we will create a module object and make the request to fetch the API and export the file to index.js. To get data from Reddit, you need to use the search endpoint. In the Reddit API documentation, you will find more information about the search endpoint. The query parameters will be added dynamically from the HTML form.

To get this working, paste the following code into the file below:

export default {
  search: function (searchTerm, searchLimit, sortBy) {
    // fetch api of reddit
    return (
      fetch(
        `http://www.reddit.com/search.json?q=${searchTerm}&sort=${sortBy}&limit=${searchLimit}`
      )
        .then((res) => res.json())
        .then((data) => data.data.children.map((data) => data.data))
        // to get error
        .catch((err) => console.log(err))
    );
  },
};
Enter fullscreen mode Exit fullscreen mode

Now, we have to import the module to the index.js file using import reddit from './redditapi'; . This should be done in the first line of the index.js file.

Note that reddit in the inline code above is a variable that we will use to call the search function.

To get the data, which is the result in this case, we will output to the UI using the Bootstrap card. We will loop through all the results and create a card for each one. The following code will handle that.

The code below should be within the function linked to the event listener in your index.js file:

reddit.search(searchTerm, searchLimit, sortBy).then((results) => {
    let output = '<div class="card-columns">';
    // loop through post
    results.forEach((post) => {

      output += `<div class="card">
     <div class="card-body">
      <h5 class="card-title">${post.title}</h5>
      <p class="card-text">${truncateText(post.selftext, 100)}</p>
      <a href="${post.url}" target="_blank" class="btn btn-dark">Read More</a>
    </div> 
  </div>`;});
    output += "</div>";
    document.getElementById("results").innerHTML = output;
  });
Enter fullscreen mode Exit fullscreen mode

As you can see, we have appended the result to the DOM where the id=results are located in the HTML file. In the code above, I also used the function truncateText on the selftext (which contains the post details) to shorten the post.

Below is the function to implement the truncation. Paste the following code at the end of your index.js :

// truncate text
function truncateText(text, limit) {
  const shortened = text.indexOf("", limit);
  if (shortened == -1) return text;
  return text.substring(0, shortened);
}
Enter fullscreen mode Exit fullscreen mode

You can now run the Parcel server by running the following command, and you will be provided with a URL (http://localhost:1234) that can be used to access your app in a browser.

npx parcel index.html
Enter fullscreen mode Exit fullscreen mode

final app

From the image above, we can see that the search brought out the word searched, which is in card form. The “Read More" button, when clicked, will open a new tab with the content of the search for one to read.

Conclusion

In this article, we have seen how the Parcel works and how to install it globally using npm. We built an application that searches the Reddit API directly and fetches the data entered in the form.

We also found a way to filter searched items based on relevance, the latest, and the number of results you want to receive.

I would advise you to get familiar with the Reddit API documentation so that you will be able to implement more features of the API in your future projects.

Top comments (0)