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.
-
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. -
Create a project folder
mkdir api-demo && cd api-demo
-
Initialize a Node.js project
npm init -y
This creates a
package.json
file to manage dependencies. -
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! π―