Getting Started with APIs in JavaScript

πŸš€ Learn how to fetch and format API data with JavaScript & Node.js! A beginner-friendly tutorial using a Job Posting API. Perfect for your next coding project! πŸ’»βœ¨

Posted by JΓΆrg Rech on June 1, 2025 at 09:23:56

Reading Time: 7 min read

Introduction

Looking for a fun coding project this summer? 🌞 Why not explore APIs with JavaScript and Node.js! In this tutorial, you'll learn how to fetch and format data from an API, using a job postings API as an example. It's a great way to sharpen your coding skills while building something useful. Let’s dive in! πŸš€

APIs (Application Programming Interfaces) power the modern web, allowing apps to fetch real-time data like weather updates, sports scores, and even job postings. If you've ever wondered how websites display live information, APIs are the answer!

This tutorial will introduce API calls in JavaScript. You'll learn how to: Send API requests, handle JSON responses, and format and save data to a file.

To make it practical, we'll use a Job Posting API as an example. But once you master these skills, you can explore any API - from cryptocurrency prices to movie databases! πŸŽ¬πŸ“Š

Set Up Your Environment

Before we dive into the code, make sure you have Node.js installed.

  1. Check if Node.js is installed

    node -v
    

    If you see a version number (e.g., v18.0.0), you're good to go! Otherwise, download it from nodejs.org.

  2. Create a project folder

    mkdir api-demo && cd api-demo
    
  3. Initialize a Node.js project

    npm init -y
    

    This creates a package.json file to manage dependencies.

  4. Install axios (to make API calls)

    npm install axios fs
    

Now you're ready to fetch some data! πŸš€

Understanding APIs and the Job Posting API

The Daily International Job Posting API allows you to request data from a service and get results in JSON format. The Job Posting API provides real-time job listings, which we’ll use as an example.

Here’s an API request URL:

https://daily-international-job-postings.p.rapidapi.com/api/v2/jobs/search?workPlace=remote&page=1

To access it, you need an API key and then it fetches remote jobs and returns JSON like this:

{
  "result": [
    {
      "title": "Frontend Developer",
      "company": "TechCorp",
      "dateCreated": "2025-02-10T10:00:00Z"
    }
  ]
}

Get Your API Key

1️⃣ Sign up at RapidAPI (free). 2️⃣ Visit the Job Posting API page. 3️⃣ Subscribe to the freeium Basic plan and copy your x-rapidapi-key.

Fetch Data from the API

Now, let's write a script to fetch job postings using axios. First create the file fetch-jobs.js and copy the following code into it:

const axios = require("axios");
const fs = require("fs");

const API_URL = "https://daily-international-job-postings.p.rapidapi.com/api/v2/jobs/search";
const API_KEY = "YOUR_API_KEY";  // Replace with your actual key

async function fetchJobs() {
    try {
        const response = await axios.get(API_URL, {
            params: { workPlace: "remote", language: "en", page: 1 },
            headers: {
                "x-rapidapi-key": API_KEY,
                "x-rapidapi-host": "daily-international-job-postings.p.rapidapi.com"
            }
        });

        const totalCount = response.data.totalCount
        console.log(`βœ… Data received! Found ${totalCount} job postings on ${Math.ceil(totalCount / 10)} pages`);

        const jobs = response.data.result.map(job => ({
            title: job.title,
            company: job.company,
            dateCreated: job.dateCreated,
            url: job.jsonLD?.url || "No URL available"
        }));
        console.log(jobs);

        return response.data.result;
    } catch (error) {
        console.error("Error fetching data:", error.response?.data || error.message);
        return [];
    }
}

// Run the function
fetchJobs();

Run the script:

node fetch-jobs.js

If everything works, you’ll see 10 shortened job listings printed in the terminal! πŸŽ‰

Save API Data to a File

To store the results, update the function fetchJobs() of your script to write data to a file such as this:

async function fetchJobs() {
    try {
        const response = await axios.get(API_URL, {
            params: { title: "JavaScript", language: "en", page: 1 },
            headers: {
                "x-rapidapi-key": API_KEY,
                "x-rapidapi-host": "daily-international-job-postings.p.rapidapi.com"
            }
        });

        const totalCount = response.data.totalCount
        console.log(`βœ… Data received! Found ${totalCount} job postings on ${Math.ceil(totalCount / 10)} pages`);

        const jobs = response.data.result.map(job => ({
            title: job.title,
            company: job.company,
            dateCreated: job.dateCreated,
            url: job.jsonLD?.url || "No URL available"
        }));
        // console.log(jobs);

        fs.writeFileSync("jobs.json", JSON.stringify(jobs, null, 2));
        console.log(`βœ… Saved ${jobs.length} jobs to jobs.json`);

        return response.data.result;
    } catch (error) {
        console.error("Error fetching data:", error.response?.data || error.message);
        return [];
    }
}

fetchJobs();

Now, your job listings are saved in jobs.json for later use!

Format API Data as a Table

JSON can be hard to read, so let’s display job listings as a HTML table that you can use in a Webpage:

const fs = require("fs");

// Read jobs from file
const jobs = JSON.parse(fs.readFileSync("jobs.json", "utf8"));

// Build the HTML table string
let htmlTable = `<table border="1">
  <thead>
    <tr>
      <th>Date</th>
      <th>Title</th>
      <th>Company</th>
      <th>URL</th>
    </tr>
  </thead>
  <tbody>
`;

jobs.forEach(job => {
    const date = job.dateCreated.split("T")[0];
    const title = job.title;
    const company = job.company;
    const url = job.url;
    htmlTable += `    <tr>
      <td>${date}</td>
      <td>${title}</td>
      <td>${company}</td>
      <td><a href="${url}" target="_blank">${url}</a></td>
    </tr>
`;
});

htmlTable += `  </tbody>
</table>`;

// Print the HTML table
console.log(htmlTable);

Run it:

node format-jobs.js

Now, job listings appear in a HTML table in your terminal!

Explore More!

πŸŽ‰ Congrats! You've now learned how to: βœ… Fetch API data with axios. βœ… Handle JSON responses. βœ… Save data to a file. βœ… Format and display data in a HTML table.

Next, try: βœ… Filter jobs by workPlace (e.g., workPlace=Remote). βœ… Paginate multiple pages (e.g., page=2). βœ… Sort jobs by date (i.e., in JavaScript). βœ… Fetching other APIs (location data, transportation, etc.).

Final Thoughts

πŸš€ APIs power the web and you just built a real-world project using Node.js! Now go explore APIs, automate tasks, and build something awesome.

Happy coding! 🎯

Build something great!

Unleash the full potential of our high-quality job postings to achieve your business objectives and gain a competitive edge in your industry!

Excellent Service

Our reliable services are tailored to meet your needs, helping you achieve your goals with confidence.

Scalable Solution

Our global coverage is designed to support your use-case, enabling you to easily add new markets.

Fast Set-up

Download JSON files from AWS S3 and pump them into your Databases or connect to our API in minutes.

Explore our Data!