Building REST APIs

1/6/2025

Building REST APIs

Learn how to build RESTful APIs with Node.js and Express.

REST Principles

  • Stateless: Each request contains all needed information
  • Uniform Interface: Consistent API design
  • Resource-Based: URLs represent resources

Complete CRUD Example

javascript
const express = require('express')
const app = express()
app.use(express.json())

let users = []

// GET all users
app.get('/api/users', (req, res) => {
  res.json(users)
})

// GET single user
app.get('/api/users/:id', (req, res) => {
  const user = users.find(u => u.id === req.params.id)
  if (!user) return res.status(404).json({ error: 'Not found' })
  res.json(user)
})

// POST create user
app.post('/api/users', (req, res) => {
  const user = { id: Date.now().toString(), ...req.body }
  users.push(user)
  res.status(201).json(user)
})

// PUT update user
app.put('/api/users/:id', (req, res) => {
  const index = users.findIndex(u => u.id === req.params.id)
  if (index === -1) return res.status(404).json({ error: 'Not found' })
  users[index] = { ...users[index], ...req.body }
  res.json(users[index])
})

// DELETE user
app.delete('/api/users/:id', (req, res) => {
  users = users.filter(u => u.id !== req.params.id)
  res.status(204).send()
})

Error Handling

javascript
app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).json({ error: 'Something went wrong!' })
})