Tutorial: Building Your First REST API with Node.js

Difficulty: Beginner Beginner | Duration: 45 minutes | Prerequisites: Basic JavaScript knowledge

Last updated:


What You'll Learn

In this tutorial, you'll learn how to build a complete REST API from scratch using Node.js and Express. By the end, you'll have a working API that can:


Table of Contents

  1. Setting Up Your Project
  2. Installing Express
  3. Creating Your First Route
  4. Connecting to a Database
  5. Implementing CRUD Operations
  6. Adding Validation
  7. Error Handling
  8. Testing Your API
  9. Next Steps

Step 1: Setting Up Your Project

First, let's create a new directory for our project and initialize it with npm.

Create the Project Directory

mkdir my-first-api
cd my-first-api

Initialize npm

npm init -y

This creates a package.json file with default settings. Your file should look like this:

{
  "name": "my-first-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Tip: The -y flag accepts all default options. You can run npm init without it to customize each field.

Progress: Step 1/8


Step 2: Installing Express

Express is a minimal and flexible Node.js web application framework. Let's install it:

npm install express

This will add Express to your package.json dependencies:

{
  "dependencies": {
    "express": "^4.18.2"
  }
}

Additional Dependencies

We'll also need a few more packages for our API:

npm install dotenv mongoose joi cors
dotenv
Loads environment variables from a .env file
mongoose
MongoDB object modeling tool
joi
Schema validation library
cors
Enables Cross-Origin Resource Sharing

Development Dependencies

npm install --save-dev nodemon

nodemon automatically restarts your server when files change. Let's add a start script to package.json:

{
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js"
  }
}

Progress: Step 2/8


Step 3: Creating Your First Route

Create a new file called server.js in your project root:

// server.js
const express = require('express');
const app = express();
const PORT = 3000;

// Middleware to parse JSON
app.use(express.json());

// Your first route!
app.get('/', (req, res) => {
  res.json({ message: 'Hello, World!' });
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Understanding the Code

Let's break down what each part does:

  1. require('express') - Imports the Express module
  2. express() - Creates an Express application
  3. app.use(express.json()) - Adds middleware to parse JSON request bodies
  4. app.get('/', ...) - Defines a route that responds to GET requests
  5. app.listen(PORT, ...) - Starts the server on port 3000

Test Your Server

Run the server:

npm run dev

You should see:

Server is running on port 3000

Open your browser and visit http://localhost:3000. You should see:

{
  "message": "Hello, World!"
}

Success! Your first API endpoint is working.

Progress: Step 3/8


Step 4: Connecting to a Database

Let's connect to MongoDB using Mongoose. First, create a .env file:

# .env
PORT=3000
MONGODB_URI=mongodb://localhost:27017/myapi

Important: Add .env to your .gitignore file to keep your secrets safe!

Create a new file config/database.js:

// config/database.js
const mongoose = require('mongoose');

const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log('MongoDB connected successfully');
  } catch (error) {
    console.error('MongoDB connection error:', error);
    process.exit(1);
  }
};

module.exports = connectDB;

Update server.js to use the database connection:

// server.js
require('dotenv').config();
const express = require('express');
const connectDB = require('./config/database');

const app = express();
const PORT = process.env.PORT || 3000;

// Connect to database
connectDB();

// Middleware
app.use(express.json());

// Routes
app.get('/', (req, res) => {
  res.json({ message: 'API is running' });
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Progress: Step 4/8


Step 5: Implementing CRUD Operations

CRUD operations are the foundation of any API. Let's build a simple user management system.

Create a User Model

Create models/User.js:

// models/User.js
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  email: {
    type: String,
    required: true,
    unique: true,
    lowercase: true
  },
  age: {
    type: Number,
    min: 0,
    max: 120
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('User', userSchema);

Create Routes

Create routes/users.js:

// routes/users.js
const express = require('express');
const router = express.Router();
const User = require('../models/User');

// CREATE - Add new user
router.post('/', async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.status(201).json(user);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

// READ - Get all users
router.get('/', async (req, res) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// READ - Get user by ID
router.get('/:id', async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.json(user);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// UPDATE - Update user by ID
router.put('/:id', async (req, res) => {
  try {
    const user = await User.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    );
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.json(user);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

// DELETE - Delete user by ID
router.delete('/:id', async (req, res) => {
  try {
    const user = await User.findByIdAndDelete(req.params.id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.json({ message: 'User deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;

Update server.js to use the routes:

// Add this line with other requires
const userRoutes = require('./routes/users');

// Add this line after middleware
app.use('/api/users', userRoutes);

CRUD Operations Summary

Operation HTTP Method Endpoint Description
Create POST /api/users Create a new user
Read GET /api/users Get all users
Read GET /api/users/:id Get user by ID
Update PUT /api/users/:id Update user by ID
Delete DELETE /api/users/:id Delete user by ID

Progress: Step 5/8


Step 6: Adding Validation

Input validation is crucial for API security and data integrity. Let's use Joi to validate requests.

Create middleware/validation.js:

// middleware/validation.js
const Joi = require('joi');

const userSchema = Joi.object({
  name: Joi.string()
    .min(3)
    .max(50)
    .required()
    .messages({
      'string.min': 'Name must be at least 3 characters',
      'string.max': 'Name cannot exceed 50 characters',
      'any.required': 'Name is required'
    }),

  email: Joi.string()
    .email()
    .required()
    .messages({
      'string.email': 'Please provide a valid email',
      'any.required': 'Email is required'
    }),

  age: Joi.number()
    .min(0)
    .max(120)
    .optional()
    .messages({
      'number.min': 'Age must be at least 0',
      'number.max': 'Age cannot exceed 120'
    })
});

const validateUser = (req, res, next) => {
  const { error } = userSchema.validate(req.body);

  if (error) {
    return res.status(400).json({
      error: error.details[0].message
    });
  }

  next();
};

module.exports = { validateUser };

Update routes/users.js to use validation:

const { validateUser } = require('../middleware/validation');

// Apply validation to POST and PUT routes
router.post('/', validateUser, async (req, res) => {
  // ... existing code
});

router.put('/:id', validateUser, async (req, res) => {
  // ... existing code
});

Testing Validation

Try creating a user with invalid data:

POST /api/users
Content-Type: application/json

{
  "name": "AB",
  "email": "invalid-email"
}

Response:

{
  "error": "Name must be at least 3 characters"
}

Progress: Step 6/8


Step 7: Error Handling

Proper error handling makes your API more robust and user-friendly.

Create middleware/errorHandler.js:

// middleware/errorHandler.js
const errorHandler = (err, req, res, next) => {
  console.error(err.stack);

  // Mongoose validation error
  if (err.name === 'ValidationError') {
    return res.status(400).json({
      error: 'Validation Error',
      details: Object.values(err.errors).map(e => e.message)
    });
  }

  // Mongoose duplicate key error
  if (err.code === 11000) {
    return res.status(400).json({
      error: 'Duplicate Error',
      message: 'A user with this email already exists'
    });
  }

  // Mongoose cast error (invalid ID)
  if (err.name === 'CastError') {
    return res.status(400).json({
      error: 'Invalid ID format'
    });
  }

  // Default error
  res.status(500).json({
    error: 'Internal Server Error',
    message: err.message
  });
};

module.exports = errorHandler;

Add to server.js (at the end, after all routes):

const errorHandler = require('./middleware/errorHandler');

// Error handling middleware (must be last)
app.use(errorHandler);

Common HTTP Status Codes

Code Name When to Use
200 OK Request succeeded
201 Created Resource created successfully
400 Bad Request Invalid request data
404 Not Found Resource not found
500 Internal Server Error Server error occurred

Progress: Step 7/8


Step 8: Testing Your API

Let's test all our endpoints using curl or a tool like Postman.

Create a User

curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Alice Johnson",
    "email": "alice@example.com",
    "age": 28
  }'

Response:

{
  "_id": "65a1b2c3d4e5f6789abcdef0",
  "name": "Alice Johnson",
  "email": "alice@example.com",
  "age": 28,
  "createdAt": "2024-01-15T10:30:00.000Z"
}

Get All Users

curl http://localhost:3000/api/users

Get User by ID

curl http://localhost:3000/api/users/65a1b2c3d4e5f6789abcdef0

Update a User

curl -X PUT http://localhost:3000/api/users/65a1b2c3d4e5f6789abcdef0 \
  -H "Content-Type: application/json" \
  -d '{
    "age": 29
  }'

Delete a User

curl -X DELETE http://localhost:3000/api/users/65a1b2c3d4e5f6789abcdef0

Testing Checklist

Endpoints Tested

Progress: Step 8/8 - Complete!


Next Steps

Congratulations! You've built a complete REST API. Here's what to learn next:

Recommended Improvements

  1. Authentication & Authorization
    • Add JWT-based authentication
    • Implement role-based access control
    • Secure sensitive endpoints
  2. Advanced Features
    • Pagination for list endpoints
    • Search and filtering
    • Rate limiting
    • API versioning
  3. Testing
    • Write unit tests with Jest
    • Integration tests with Supertest
    • Set up CI/CD pipeline
  4. Documentation
    • Generate API docs with Swagger
    • Add request/response examples
    • Document error codes
  5. Deployment
    • Deploy to cloud platforms (Heroku, AWS, etc.)
    • Set up environment variables
    • Configure logging and monitoring

Additional Resources

  • Express.js Official Documentation
  • Mongoose Documentation
  • REST API Best Practices Guide
  • Node.js Security Checklist
  • API Testing Tutorial
  • Complete Project Structure

    my-first-api/
    ├── config/
    │   └── database.js
    ├── middleware/
    │   ├── errorHandler.js
    │   └── validation.js
    ├── models/
    │   └── User.js
    ├── routes/
    │   └── users.js
    ├── .env
    ├── .gitignore
    ├── package.json
    └── server.js