QR CookingNotes

CookingNotes

Your Personal Recipe Book

Get it on Google Play
QR FiNoteMe

FiNoteMe

Smart Finance Tracker

Get it on Google Play
webdev Ready to make your REST API cleaner and safer? In this tutorial, we’ll learn how to organize routes using Express Router and add simple input validation

Organizing Your Node.js REST API with Express Router and Input Validation

5 Min Read Verified Content

Step 1: Why Organize Routes?

Imagine your code is like a big kitchen. 🍳
If all the ingredients, pots, and pans are thrown in one corner, cooking gets messy fast!

Right now, all our API routes are in server.js. That’s fine for small projects, but as we grow, it’s better to organize routes in separate files. This makes your project clean, readable, and easier to maintain.



Step 2: Create a Routes Folder

  1. In your project folder, make a new folder called routes:

mkdir routes
  1. Inside routes, create a file called users.js.

This file will hold all the user-related routes.



Step 3: Move Routes into users.js

In routes/users.js, put this code:

const express = require('express'); const router = express.Router(); const sqlite3 = require('sqlite3').verbose(); // Database connection const db = new sqlite3.Database('./database.db'); // GET all users router.get('/', (req, res) => { db.all('SELECT * FROM users', [], (err, rows) => { if (err) return res.status(500).json({ error: err.message }); res.json(rows); }); }); // GET user by ID router.get('/:id', (req, res) => { const { id } = req.params; db.get('SELECT * FROM users WHERE id = ?', [id], (err, row) => { if (err) return res.status(500).json({ error: err.message }); res.json(row); }); }); // POST create new user router.post('/', (req, res) => { const { name, email } = req.body; // Simple input validation if (!name || !email) { return res.status(400).json({ error: 'Name and email are required!' }); } db.run('INSERT INTO users (name, email) VALUES (?, ?)', [name, email], function(err) { if (err) return res.status(500).json({ error: err.message }); res.json({ id: this.lastID, name, email }); }); }); // PUT update user router.put('/:id', (req, res) => { const { id } = req.params; const { name, email } = req.body; if (!name || !email) { return res.status(400).json({ error: 'Name and email are required!' }); } db.run('UPDATE users SET name = ?, email = ? WHERE id = ?', [name, email, id], function(err) { if (err) return res.status(500).json({ error: err.message }); res.json({ updatedID: id, name, email }); }); }); // DELETE user router.delete('/:id', (req, res) => { const { id } = req.params; db.run('DELETE FROM users WHERE id = ?', [id], function(err) { if (err) return res.status(500).json({ error: err.message }); res.json({ deletedID: id }); }); }); module.exports = router;

Notice how we added simple input validation. If someone tries to create a user without a name or email, our API will politely refuse. 😊



Step 4: Update server.js

Now we need to tell server.js to use this new route file:

const express = require('express'); const bodyParser = require('body-parser'); const userRoutes = require('./routes/users'); const app = express(); const PORT = 3000; app.use(bodyParser.json()); // Use the user routes app.use('/users', userRoutes); app.get('/', (req, res) => { res.send('Hello, young coder! Your organized REST API is running. 🚀'); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });

Now, all user routes live in routes/users.js and server.js stays clean and simple.



Step 5: Test Everything

  • Open Postman or use curl to check that all endpoints (GET /users, POST /users, etc.) still work.

  • Try sending invalid data to POST /users to see the validation in action.



Step 6: Next Tips from Your Coding Grandpa 😄

  • You can create more route files for other features like products.js or tasks.js.

  • Learn about Express middleware to add authentication or logging.

  • Always keep routes small and organized—like tidy drawers in your kitchen!

Advertisement
Back to Webdev