EliteCode

Tutorial

15 min read

Building a REST API with Node.js and Express

Nirvik Basnet
Nirvik Basnet

Lead InstructorMarch 15, 2024

Building a REST API with Node.js and Express

In this tutorial, we'll learn how to build a robust REST API using Node.js and Express. We'll cover everything from setup to deployment.

Prerequisites

  • Node.js installed on your machine
  • Basic JavaScript knowledge
  • Understanding of HTTP methods

Project Setup

First, let's create a new project and install the necessary dependencies:

mkdir rest-api-tutorial cd rest-api-tutorial npm init -y npm install express dotenv mongoose

Creating the Server

Create a new file called server.js:

const express = require('express'); const dotenv = require('dotenv'); // Load environment variables dotenv.config(); // Initialize express const app = express(); // Middleware app.use(express.json()); // Basic route app.get('/', (req, res) => { res.json({ message: 'Welcome to our API!' }); }); // Start server const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

Adding Routes

Create a new folder called routes and add users.js:

const express = require('express'); const router = express.Router(); // Get all users router.get('/', (req, res) => { res.json({ users: [] }); }); // Create new user router.post('/', (req, res) => { const { name, email } = req.body; // Add validation here res.status(201).json({ message: 'User created' }); }); module.exports = router;

Error Handling

Create a middleware for handling errors:

// middleware/error.js const errorHandler = (err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ error: { message: err.message || 'Internal Server Error', status: err.status || 500 } }); }; module.exports = errorHandler;

Testing the API

You can test your API using tools like Postman or curl:

# Get all users curl http://localhost:5000/api/users # Create a new user curl -X POST http://localhost:5000/api/users \ -H "Content-Type: application/json" \ -d '{"name": "John Doe", "email": "john@example.com"}'

Best Practices

  1. Always validate input data
  2. Use proper HTTP status codes
  3. Implement rate limiting
  4. Add authentication and authorization
  5. Document your API

Conclusion

You now have a basic REST API setup with Node.js and Express. This foundation can be extended with additional features like:

  • Database integration
  • Authentication
  • File uploads
  • Rate limiting
  • API documentation

Remember to follow REST principles and maintain clean code structure as your API grows.

Tags
Node.js
Express
API
Backend