We need to create an Express API server that can handle various HTTP requests for managing artists, albums, and songs. The server needs to:
Parse and handle JSON requests, implement various route handlers for CRUD operations, and maintain proper HTTP status codes and response formats. Think of this like building a music library management system where we need to organize and access different pieces of musical content.
const express = require('express');
const app = express();
// Enable JSON parsing for incoming requests
app.use(express.json());
// Optional debugging middleware to log request bodies
app.use((req, res, next) => {
console.log('Request Body:', req.body);
next();
});
// Get all artists
app.get('/artists', (req, res) => {
res.json(getAllArtists());
});
// Add a new artist
app.post('/artists', (req, res) => {
res.status(201);
res.json(addArtist(req.body));
});
// Get latest artist
app.get('/artists/latest', (req, res) => {
res.json(getLatestArtist());
});
// Get albums for latest artist
app.get('/artists/latest/albums', (req, res) => {
res.json(getAlbumsForLatestArtist());
});
The route handlers follow a consistent pattern:
1. Define the HTTP method and path
2. Receive the request and extract needed data
3. Process the request using imported functions
4. Send appropriate response with correct status code
// Get specific artist
app.get('/artists/:artistId', (req, res) => {
res.json(getArtistByArtistId(req.params.artistId));
});
// Update artist
app.put('/artists/:artistId', (req, res) => {
res.json(editArtistByArtistId(req.params.artistId, req.body));
});
// Delete artist
app.delete('/artists/:artistId', (req, res) => {
deleteArtistByArtistId(req.params.artistId);
res.json({ message: 'Successfully deleted' });
});
// Get artist's albums
app.get('/artists/:artistId/albums', (req, res) => {
res.json(getAlbumsByArtistId(req.params.artistId));
});
This pattern of route handling is commonly used in:
- Music streaming services (Spotify, Apple Music)
- E-commerce platforms (product categories and items)
- Content management systems (articles and comments)
- Social media platforms (users and posts)
1. RESTful Route Structure:
Think of your API routes like a well-organized filing system:
- /artists (the main artists folder)
- /artists/:artistId (a specific artist's file)
- /artists/:artistId/albums (the albums subfolder for an artist)
2. HTTP Methods as Actions:
Think of HTTP methods as different types of instructions:
- GET: Reading a file
- POST: Creating a new file
- PUT/PATCH: Updating an existing file
- DELETE: Removing a file
// Example of error handling middleware
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({
message: 'Something went wrong!',
error: err.message
});
});
// Example of validation
app.post('/artists', (req, res) => {
if (!req.body.name) {
return res.status(400).json({
message: 'Artist name is required'
});
}
const newArtist = addArtist(req.body);
res.status(201).json(newArtist);
});
When testing your routes, consider these scenarios:
1. Happy path: Send valid data and verify correct response
2. Missing data: Ensure proper error handling
3. Invalid IDs: Check how non-existent resources are handled
4. Wrong HTTP methods: Verify proper method handling
Remember: Your API is like a librarian - it needs to handle requests politely, know where to find things, and maintain organization even when things go wrong.