← All writing

Building a REST API with Node.js

Step-by-step guide to building a scalable REST API using Node.js and Express.

Building a REST API is a fundamental skill for any backend developer. In this guide, we’ll walk through building a scalable REST API using Node.js and Express.

Setting Up the Project

First, let’s initialize our project and install the necessary dependencies:

npm init -y
npm install express dotenv
npm install -D nodemon

Basic Server Setup

Create an index.js file with a basic Express server:

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

app.use(express.json())

app.get("/", (req, res) => {
  res.json({ message: "Welcome to the API" })
})

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

Creating Routes

Organize your routes in separate files for better maintainability:

// routes/users.js
const express = require("express")
const router = express.Router()

// GET /users
router.get("/", async (req, res) => {
  try {
    const users = await getUsers()
    res.json(users)
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
})

// GET /users/:id
router.get("/:id", async (req, res) => {
  try {
    const user = await getUserById(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 })
  }
})

// POST /users
router.post("/", async (req, res) => {
  try {
    const user = await createUser(req.body)
    res.status(201).json(user)
  } catch (error) {
    res.status(400).json({ error: error.message })
  }
})

module.exports = router

Error Handling

Create a centralized error handler:

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

module.exports = errorHandler

Middleware

Add useful middleware like CORS and request logging:

const cors = require("cors")
const morgan = require("morgan")

app.use(cors())
app.use(morgan("combined"))

Environment Variables

Use environment variables for configuration:

PORT=3000
NODE_ENV=development
DATABASE_URL=mongodb://localhost:27017/myapp

Conclusion

This is a basic structure for a REST API. As your API grows, consider adding:

  • Authentication and authorization

  • Input validation

  • Rate limiting

  • API documentation (Swagger/OpenAPI)

  • Testing

  • Logging and monitoring

Happy coding!