Adding Blog Articles Cards to our Site in vanilla Javascript
Tags: webdev, javascript, beginners, api
Published: 2021-08-30 10:41:54

Hi there Dev community! I hope you're having a wonderful day! My name's Edmund, and I share this blog with my friend and business partner, Katie. We're planning to use this blog as a way to share things we're trying, and just enjoy the learning process with this great community! It's a great way to think differently about the work we're doing and we think it'll help us grow as developers.

Today, I thought I'd share some information on how we've recently used the Dev.to API to share our blog posts on our website, as an introduction to working with APIs and building html on the fly with vanilla javascript.

The term "API" gets used a lot in development circles, and as the wisdom of the early comic book era goes, every issue might be someone's first issue. For those encountering this concept for the first time, an API is an [Application Programming Interface](https://en.wikipedia.org/wiki/API). Basically, when a program wants to let other developers use the data it's gathered or run the functions that it has they develop a set of code that let's those other developers make requests automatically. To do this, they'll define and publicise what data they have and what the requests look like.  

Working with APIs is really awesome when you think about it! It allows for all of these different development efforts on specific topics and domains to be combined into the cool applications that we get to see and use on a day to day basis.

So, let's dive into how we can go about using an API to gather and display data.

## Exploring the Dev.to API
When I talk about the Dev.to API, what I really mean is the [Forem](https://www.forem.com/) API. Dev.to is built on top of the Forem software (along with other online communities) so we can use Forem's API to get to all the data that Dev.to exposes. We could use the same API to get the data from other online communities built on Forem too. Neat!

The Forem API is a type called a [REST API](https://restfulapi.net/). There's a lot of design principles and rules that ought to be followed when building a RESTful API. But generally speaking, REST is a way of defining the objects in your system as "resources" which you then interact with using different methods. And most often on the web, this implemented using urls and HTTP verbs; GET/PUT/POST/DELETE etc (although this is not universal).

As an example, say we had an API that let us ask about the fruit in a fruit bowl. It would probably have a resource called _fruit_ available at "fruit-bowl/fruit". And if we wanted to ask what pieces of fruit were in the bowl, we could send a GET request to the fruit resource. The API would then know that what you want is just the list of fruit, and it could send you that back.

Because we know that Forem uses a REST api, and is in fact using urls for resources and http verbs as the methods, we know that what we're looking for the right combo of verb and url, to get at the data we want.

The first thing you'll need when working with an API (ideally) is an API reference or API document. This is the [Forem API Reference](https://developers.forem.com/api). The quality of reference documents can be a bit hit and miss, but the Forem documentation is really good. It's well structured with clear examples which work out of the box.

To build our collection of blog article links into our site, we'll need to be able to find all the articles by a certain user (us), go through each one and take the information which will help users on our site choose the post they're interested in, and then display that as clickable item which will take them to the actual post on Dev.to.

Luckily, the Forem API has an _articles_ resource **and** they're [documentation](https://developers.forem.com/api#operation/getArticles) even has an example for retrieving just the articles by a single user. Even better, we can see an example of the data that we get back if we retrieve that resource. Brilliant!

![Image of the dev.to api reference website](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5x3q0ur7ryv0evqfi4fi.png)

For this simple application, that's all we'll need. But take some time to explore the other resources and parameters available, because there's all kinds of things you could do!

## Fetching the Articles
Now that we know that we need to make an HTTP GET request to the articles url, we need to get into the editor and figure out how we can do that!

Luckily, javascript has a convenient function called [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) which does exactly what we want. It makes a GET request to the given url, and returns you the data. 

Let's create a very short sample page and try that out. Here's just a placeholder html page which includes a script at the bottom, which will do the work for us:
```html
<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="" />
    <title>ClearJoy Articles</title>
</head>

<body>
    <main>
    </main>
    <script src="./collection.js"></script>
</body>

</html>
```

And here's the collection script:
 
```javascript
fetchArticles().then(
    function(value) { console.log(value) }
)

async function fetchArticles() {
    const response = await fetch("https://dev.to/api/articles?username=ben");
    return response.json();
}
```
If you open up the html page in a browser and take a gander at your browser console, you'll be able to see the response we got back from Dev.to with all the articles for the user "ben". Ben appears to be a handy user that the documentation uses to show off how the requests work, but feel free to substitute your username if you'd prefer!

![Image of the brave browser with the console open showing some json](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ja918c8vbgl7xzewey4k.png)

So there's quite a few things to note about that. First off, you'll see that rather than just calling fetch and returning the data in a single line, we ended up wrapping our call in an _async_ function, and calling _await_ on it. _async_ in javascript is a big topic in and of itself, and I'm definitely not the best person to discuss it in any detail, but the important point is that when we're making a call to web server, we have no idea how long that could take. The server could be on the other side of the world! It could be busy. So the time to get our response could be different. And in a lot of cases we don't want to have to wait for the result before we do anything else. We can be getting on with other stuff, and then come back and finish off whatever we were needing that data for when it arrives. In cases like that, we can use `async` functions to make the call, and _then_ do something when the result is returned. 

And that's exactly the syntax! We call our async function, and we call `.then()` on the result of that which in this case we're passing a function to execute with the result to just call `console.log()`. We also could (and should) pass a second parameter to `then()` which is the function to call if an error occurs, but for now we won't worry too much.

The other important thing to note is that we convert the response to [json](https://www.json.org/json-en.html) before returning from our function. If you've not met json before, it's just a way to structure data as text so that we can easily explore it. We'll need that for later, but it also makes the response pretty easy to read because tools like our browser have built in json parsers.

Right! Now we've got our data, I'm always a fan of a bit of a refactor. Keeping the code clean, is important!

```javascript
const username = "ben";
const articleUrl = "https://dev.to/api/articles";
const usernameQueryParam = "username=";

fetchArticles().then(
    function(value) { createArticleCollection(value) },
    function(error) { console.log(error) }
)

async function fetchArticles() {
    const response = await fetch(`${articleUrl}?${usernameQueryParam}${username}`);
    return response.json();
}

function createArticleCollection(articles) {
    console.log(articles);
}
```

## Constructing HTML Elements
Now that we have our articles, we need to convert them into html elements on our page. Luckily, javascript also makes that super easy!

Take a look at the [Dom Document](https://www.w3schools.com/js/js_htmldom_document.asp). This allows us to interact with the html page that the script is loaded with, **and** gives us access to the function `document.createElement()`.

Using this, we can create a div, and an anchor element, in much the same way as we would when writing just the html.

Here's what our function looks like:

```javascript
function createArticleCollection(articles) {
    let articleCollection = document.getElementById("articleCollection");

    articles.forEach(article => {
        let articleTitle = document.createElement("p");
        articleTitle.innerHTML = article.title;

        let articleItem = document.createElement("div");
        articleItem.append(articleTitle);

        let blogLink = document.createElement("a");
        blogLink.setAttribute("href", article.url);
        blogLink.appendChild(articleItem);

        articleCollection.appendChild(blogLink);
    });
}
```

You'll see that we first search our html document for an element with the id "articleCollection". This is because we need something to add all of the articles that we're about to create to. So I had to update the main section of my placeholder html to be:

```html
<main>
        <div id="articleCollection"></div>
</main>
```
After that, we work through each article that we got from making our api request and we make a link for it out of a _p_ element as the title, a _div_ element to hold the title (and any other stuff we want to add later), and an _a_ element to link to the blog post on Dev.to. As we go through, we append each piece to the piece that contains it, so that we end up with a single package that contains everything we want; in this case that's our `blogLink` variable. We then append that to our article collection and we get:

![Screenshot of web page with list of dev.to article links](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8yen55r5c36nmaq9rf5c.png)

Success!

Something I glossed over a bit was how we actually got the information from our article. You can see where we're creating the _p_ element, that I set the `innerHTML = article.title`. Because we told the computer to convert the response to json, we can interact with it like any object in javascript. That means we can just retrieve properties by name, and as long as they have data associated with them, we'll get it back.

So in this case we access _title_ and the Forem API returned an article object with a title field, so we get that back.

We do the same thing further down with the _a_ element. But this time, rather than setting `innerHTML` we needed to add an attribute to the element (just as we do when we write the html manually). 

Now we have the power to take anything from that data and throw it onto the page! So I put some of that together and came out with:

![Screenshot of web page with un-styled blog posts, including header images](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qlb3yv5ytco6udelu6ge.png)

This is just a simple collection. We could add all kinds of things, like tags used or average read time. I also refactored here. Small functions are our friends and we should always look for a chance to make some!

## Styling the Collection
The last thing we need to do is apply some styles to this blog collection. As it is, it's not very readable or enjoyable.

But thankfully, now we're in the realm of html, so all we have to do is add a class to the elements we've been building and let our css take care of the rest.

Adding a class to an `htmlElement` in javascript is just as easy as it has been to add an attribtue.

```javascript
articles.forEach(article => {
    let image = createImage(article.social_image);
    let details = createBlogDetails(article);

    let articleItem = document.createElement("div");
    articleItem.append(image, details);

    articleItem.classList.add("article-item");

    articleCollection.appendChild(articleItem);
});
```
This is what my foreach loop looks like now. You can see just before we append the article to the collection, now we add a string to the classList array on our article item div. We can then style it as normal with some css.

![Screenshot of articles as simple cards](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8pfld0j1wvz8fzuvep17.png)

It's not super pretty, but you get the idea. We can style it however we'd like from here on out, because it's all just html, css, and javscript at the end of the day.

## Conclusion
APIs are great, and once you've gone through one or two, you'll find that many APIs (particularly in the web world) work in kind of the same way. So if this was your first time meeting one, I hope you were able to get something out of this article that you can apply to the code you write in the future.

Thanks for reading! Have a wonderful day!