Let's think this through for a second
In this project, we'll build a small Node.js command-line tool called user-cli that calls the Users API. We're putting to use what we learned in the Auth Overview and Bearer Token lessons — how to put Authorization in the header — and the Endpoint Anatomy lesson — how to tell apart the Base URL and the Path. Throughout the project, we'll avoid hardcoding the token in the code and instead manage it from a single config file. This part is the foundation, so getting it solid now means Part 2 and Part 3 will be easy to build on top of.
Let's actually build it
In your terminal, run mkdir user-cli && cd user-cli, then create package.json with npm init -y. Create a config.js file and set it up to read API_BASE_URL and API_TOKEN from process.env. Then, in api.js, write a getUsers(page, limit) function that adds an Authorization: Bearer <token> header, sends a GET request to /v1/users?page=&limit=, and logs the JSON response with console.log. Check that the shape of that response matches the { data, meta } pattern you learned about in the Response Shape lesson.
Code Example
// config.js
require('dotenv').config();
module.exports = {
API_BASE_URL: process.env.API_BASE_URL || 'https://api.example.com/v1',
API_TOKEN: process.env.API_TOKEN, // .env ထဲမှာသာ ထားပါ
};
// api.js
const { API_BASE_URL, API_TOKEN } = require('./config');
async function getUsers(page = 1, limit = 10) {
const url = `${API_BASE_URL}/users?page=${page}&limit=${limit}`;
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${API_TOKEN}`,
Accept: 'application/json',
},
});
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
}
getUsers(1, 5).then(console.log);The terminal will print out the first page of the users list as JSON, in the shape { data: [...], meta: { page, limit, total } }.5-Minute Try-It
In 5 minutes: create a .env file, add API_TOKEN=your_test_token, install the dotenv package, and run getUsers() to see if it works.
A Quick Word of Caution
If you commit your .env file without adding it to .gitignore, your token could leak — so set up .gitignore right from the start of the project.