Market Flash
Mega-cap AI budgets are moving from pilot projects to core planning cycles
Cyber resilience spending is climbing as boards rethink operational risk
CEO succession is turning into a valuation issue for large public companies
Payments and software deal talk is heating up again across the market
Margin discipline is still winning earnings season when demand stays intact
API Designbotcrawl

RESTful API Design: Best Practices and Common Pitfalls

A well-designed API is the backbone of any modern application. This guide covers the principles, patterns, and pitfalls of RESTful API design that every backend developer should master.

// Express.js API with proper error handling and validation
import express from "express";
import { z } from "zod";

const router = express.Router();

// Validation middleware
const validate = (schema) => (req, res, next) => {
  try {
    schema.parse(req.body);
    next();
  } catch (error) {
    res.status(400).json({
      error: "Validation Error",
      details: error.errors.map(e => ({
        field: e.path.join("."),
        message: e.message,
      })),
    });
  }
};

// Pagination helper
const paginate = (query) => {
  const page = Math.max(1, parseInt(query.page) || 1);
  const limit = Math.min(100, Math.max(1, parseInt(query.limit) || 20));
  return { skip: (page - 1) * limit, take: limit, page, limit };
};

router.get("/api/v2/posts", async (req, res) => {
  const { skip, take, page, limit } = paginate(req.query);
  const [posts, total] = await Promise.all([
    db.post.findMany({ skip, take, orderBy: { createdAt: "desc" } }),
    db.post.count(),
  ]);

  res.json({
    data: posts,
    meta: {
      page, limit, total,
      totalPages: Math.ceil(total / limit),
      hasNext: page * limit < total,
    },
  });
});

More Stories