100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
HomeBlogLearn Node.js Through Building a Music API
Learn Through Hobbies

Learn Node.js Through Building a Music API

SV

SkillVeris Team

Content Team

May 18, 2026 11 min read
Share:
Learn Node.js Through Building a Music API
Key Takeaway

Node.js brings JavaScript to the server and Express adds HTTP routing, so together they create REST APIs in minutes.

In this guide, you'll learn:

  • A music playlist API teaches every REST verb: GET, POST, PUT, and DELETE.
  • Route parameters like /tracks/:id capture values from the URL and always arrive as strings.
  • Middleware functions run on every request and must call next() to continue to the route handler.
  • Loading and saving a JSON file lets your playlist persist across server restarts.

1Why Node.js for Your First API?

If you already know JavaScript from the browser, Node.js lets you use the same language on the server. You don't need to learn a new language to build a backend — your knowledge of functions, arrays, objects, and async/await transfers directly.

Express, the most popular Node.js web framework, adds just enough structure to build real APIs without getting in your way.

A music playlist API is the ideal first project: the data model is simple (tracks with title, artist, genre, and duration), but the API covers every REST verb (GET, POST, PUT, DELETE) and the real patterns — route parameters, query filtering, and JSON request bodies — that you'll use in production.

2What We Are Building

Our music API exposes five endpoints covering the full lifecycle of a track: listing, fetching a single record, creating, updating, and deleting.

These four endpoints map cleanly onto the standard REST verbs you'll reuse on almost every API you build.

  • GET · /tracks · Return all tracks (with optional search)
  • GET · /tracks/:id · Return one track by ID
  • POST · /tracks · Add a new track
  • PUT · /tracks/:id · Update a track
  • DELETE · /tracks/:id · Delete a track

3Setup: Node.js and Express

Install the Node.js LTS release, scaffold a project folder, and add Express.

node --watch (Node 18+) restarts the server automatically on file changes — no need to install nodemon separately.

Create the project

Initialise the project and install Express.

code
# Install Node.js from nodejs.org (LTS version)
node --version # v22.x or later
# Create project
mkdir music-api && cd music-api
npm init -y
npm install express
# Create the entry file
touch index.js

package.json

Add "type": "module" to use ES module syntax (import/export), plus start and dev scripts.

code
{
  "type": "module",
  "scripts": {
    "start": "node index.js",
    "dev": "node --watch index.js"
  }
}

4Your First Route: GET /tracks

Create index.js, set up an Express app, register the JSON body parser, and define an in-memory list of tracks.

The GET /tracks handler simply returns the whole array as JSON, and app.listen() starts the server on port 3000.

index.js

Define the data store and the route, then start the server.

code
// index.js
import express from 'express';
const app = express();
app.use(express.json()); // parse JSON request bodies
// In-memory data store (we'll move to a file in section 10)
let tracks = [
  { id: 1, title: 'Blinding Lights', artist: 'The Weeknd', genre: 'pop', duration: 200 },
  { id: 2, title: 'Levitating', artist: 'Dua Lipa', genre: 'pop', duration: 203 },
  { id: 3, title: 'Shape of You', artist: 'Ed Sheeran', genre: 'pop', duration: 234 },
  { id: 4, title: 'Believer', artist: 'Imagine Dragons', genre: 'rock', duration: 204 },
];
// GET all tracks
app.get('/tracks', (req, res) => {
  res.json(tracks);
});
app.listen(3000, () => console.log('Music API running on :3000'));

Test it

Run the dev server and request the endpoint.

code
# Test it
npm run dev
curl http://localhost:3000/tracks

5Route Parameters: GET /tracks/:id

Add a handler that reads the :id segment from the URL and returns the matching track, or a 404 if none exists.

req.params.id contains the value from the URL. Route parameters are always strings, so parseInt() converts it to a number for comparison with the numeric IDs.

Fetching a single track by ID with a route parameter.
Fetching a single track by ID with a route parameter.

Single-track route

Parse the ID, find the track, and handle the not-found case.

code
// GET a single track by ID
app.get('/tracks/:id', (req, res) => {
  const id = parseInt(req.params.id); // :id is always a string
  const track = tracks.find(t => t.id === id);
  if (!track) {
    return res.status(404).json({ error: `Track ${id} not found` });
  }
  res.json(track);
});

Test it

Request an existing ID and a missing one.

code
# Test it
curl http://localhost:3000/tracks/1 # Returns Blinding Lights
curl http://localhost:3000/tracks/999 # Returns 404

6POST /tracks: Adding a Song

The POST handler reads the new track from the JSON request body, validates the required fields, assigns the next ID, and appends it to the list.

On success it responds with status 201 Created and the newly created track.

Create-track route

Validate input, build the new track, and return it.

code
// POST a new track
app.post('/tracks', (req, res) => {
  const { title, artist, genre, duration } = req.body;
  // Basic validation
  if (!title || !artist) {
    return res.status(400).json({ error: 'title and artist are required' });
  }
  const newTrack = {
    id: Math.max(0, ...tracks.map(t => t.id)) + 1,
    title,
    artist,
    genre: genre || 'unknown',
    duration: duration || 0,
  };
  tracks.push(newTrack);
  res.status(201).json(newTrack);
});

Test it

Send a JSON body with curl.

code
# Test it
curl -X POST http://localhost:3000/tracks -H "Content-Type: application/json" -d '{"title":"Flowers","artist":"Miley Cyrus","genre":"pop","duration":200}'

7PUT and DELETE Routes

PUT updates an existing track by merging the request body into the stored record while preserving its ID. DELETE removes a track by filtering it out of the array.

Both routes return 404 when the requested ID doesn't exist, and DELETE responds with 204 No Content on success.

Update and delete routes

Handle the PUT and DELETE verbs.

code
// PUT: update an existing track
app.put('/tracks/:id', (req, res) => {
  const idx = tracks.findIndex(t => t.id === parseInt(req.params.id));
  if (idx === -1) return res.status(404).json({ error: 'Not found' });
  tracks[idx] = { ...tracks[idx], ...req.body, id: tracks[idx].id };
  res.json(tracks[idx]);
});
// DELETE: remove a track
app.delete('/tracks/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const len = tracks.length;
  tracks = tracks.filter(t => t.id !== id);
  if (tracks.length === len) {
    return res.status(404).json({ error: 'Not found' });
  }
  res.status(204).send(); // 204 No Content
});

8Middleware

Middleware is a function that runs on every request before it reaches a route handler. Use it for logging, authentication, and request transformation.

The music API teaches four Node.js concepts in context — modules, Express, JSON, and async — and middleware is where several of them come together.

Each middleware receives (req, res, next) and must call next() to pass control on. You can apply middleware globally with app.use() or attach it to specific routes.

The four Node.js concepts the music API teaches in context.
The four Node.js concepts the music API teaches in context.

Middleware functions

Define a request logger and an API-key check, then wire them up.

code
// Request logger middleware
const requestLogger = (req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    console.log(`${req.method} ${req.url} ${res.statusCode} ${Date.now()-start}ms`);
  });
  next(); // MUST call next() to continue to the route handler
};
// Simple API key auth middleware
const requireApiKey = (req, res, next) => {
  if (req.headers['x-api-key'] !== process.env.API_KEY) {
    return res.status(401).json({ error: 'Invalid API key' });
  }
  next();
};
// Apply to all routes
app.use(requestLogger);
// Apply only to write operations
app.post('/tracks', requireApiKey, (req, res) => { ... });
app.put('/tracks/:id', requireApiKey, (req, res) => { ... });
app.delete('/tracks/:id', requireApiKey, (req, res) => { ... });

9Query Parameters: Search and Filter

Query parameters let you add search and filtering to the existing GET /tracks route without creating new endpoints.

Here the handler reads req.query.genre and req.query.q to narrow the result set, then returns both a total count and the matching tracks.

Filtering route

Filter by genre and a free-text query.

code
// GET /tracks?genre=pop&q=light
app.get('/tracks', (req, res) => {
  let result = [...tracks];
  if (req.query.genre) {
    result = result.filter(t =>
      t.genre.toLowerCase() === req.query.genre.toLowerCase()
    );
  }
  if (req.query.q) {
    const q = req.query.q.toLowerCase();
    result = result.filter(t =>
      t.title.toLowerCase().includes(q) ||
      t.artist.toLowerCase().includes(q)
    );
  }
  res.json({ total: result.length, tracks: result });
});

Test filtering

Pass query parameters in the URL.

code
# Test filtering
curl "http://localhost:3000/tracks?genre=pop"
curl "http://localhost:3000/tracks?q=light"

10Loading Data from a JSON File

Reading the tracks from a JSON file at startup and writing back after each change makes the playlist persist across server restarts.

For a production app, replace this with a real database (SQLite, PostgreSQL). The logic is identical; only the I/O layer changes.

File-backed storage

Load on startup and save after every write operation.

code
// Load tracks from tracks.json at startup
import { readFileSync, writeFileSync } from 'fs';
const DATA_FILE = './tracks.json';
let tracks = [];
try {
  tracks = JSON.parse(readFileSync(DATA_FILE, 'utf-8'));
} catch {
  tracks = []; // start empty if file doesn't exist
}
// Save after every write operation
function save() {
  writeFileSync(DATA_FILE, JSON.stringify(tracks, null, 2));
}
// Call save() in POST, PUT, DELETE handlers after modifying tracks

11Deploying to Railway

Railway deploys a Node app directly from a GitHub repository and can auto-detect the start command from package.json.

  • Push your project to a GitHub repository.
  • Go to railway.app, create a new project, and connect your repo.
  • Set the start command: node index.js (or let Railway auto-detect it from package.json).
  • Set environment variables (e.g. API_KEY) in Railway's Variables tab.
  • Deploy — Railway gives you a public URL like https://music-api.up.railway.app.

💡Pro Tip

Add a GET /health route that returns {"status": "ok"}. Railway (and most hosting platforms) use health-check endpoints to verify your server started correctly and is responding.

12Key Takeaways

Express gives you a small, consistent vocabulary for building REST APIs: routes, parameters, middleware, and status codes.

  • Express routes follow app.METHOD('/path', handler); route parameters use :name syntax.
  • Middleware functions receive (req, res, next) and must call next() to continue.
  • Use express.json() middleware to parse JSON request bodies.
  • HTTP status codes matter: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 404 Not Found.
  • Query parameters (req.query) enable filtering without new routes.

13What to Build Next

Extend the music API with real persistence and authentication, or build the frontend that consumes it.

  • Add a PostgreSQL database using the pg package to persist tracks properly.
  • Add user authentication with JWT (see our Full-Stack To-Do App guide for the pattern).
  • Build the React frontend that consumes this API for a full-stack music player.

14Frequently Asked Questions

What is the difference between Node.js and Express? Node.js is the JavaScript runtime — it lets you run JavaScript outside a browser. Express is a minimal web framework that runs on Node.js. Node.js alone has an HTTP module for building servers; Express adds routing, middleware, and convenience methods that make building APIs much faster.

Should I use CommonJS (require) or ES Modules (import)? Use ES Modules (import/export) for new projects — they're the standard in modern JavaScript. Add "type": "module" to package.json. You'll see CommonJS (require()) in older tutorials and codebases; both work, but don't mix them in the same project.

Is Node.js good for production APIs? Yes. Node.js powers APIs at Netflix, LinkedIn, Uber, and many other high-scale companies. Its async, event-driven architecture handles many concurrent I/O-bound requests efficiently. For CPU-bound tasks (image processing, heavy computation), Python or Go may be more suitable.

How does this compare to a Python FastAPI approach? Both build REST APIs with similar patterns: route handlers, middleware, JSON bodies, and URL parameters. FastAPI has automatic API documentation and Pydantic validation out of the box. Express is more flexible but requires more manual setup for validation. Choose based on your language preference and existing stack.

📄

Get The Print Version

Download a PDF of this article for offline reading.

About the Publisher

SV

SkillVeris Team

Content Team

We believe the best way to learn tech is through what you already love — sports, music, photography, and more.

View all posts

Never miss an update

Get the latest tutorials and guides delivered to your inbox.

No spam. Unsubscribe anytime.

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse