Building REST APIs: Complete Developer’s Guide

APIs Are the Backbone of Modern Apps

Every app you use talks to APIs. Your weather app fetches data from a weather API. Your payment processor hits a payment API. Understanding REST API design makes you a more valuable developer.

REST Design Principles

  • Stateless: Server doesn’t remember previous requests
  • Resources: Everything is a URL-addressable resource
  • HTTP Methods: Use them correctly
  • JSON: Standard exchange format

Proper HTTP Method Usage

Method Action Idempotent Example
GET Retrieve Yes GET /api/posts
POST Create No POST /api/posts
PUT Replace Yes PUT /api/posts/1
PATCH Update Yes PATCH /api/posts/1
DELETE Remove Yes DELETE /api/posts/1

Build with Express.js

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

const posts = [];

app.get('/api/posts', (req, res) => {
    res.json({ data: posts, total: posts.length });
});

app.post('/api/posts', (req, res) => {
    const { title, content } = req.body;
    if (!title) return res.status(400).json({ error: 'Title is required' });
    const post = { id: Date.now(), title, content, createdAt: new Date() };
    posts.push(post);
    res.status(201).json(post);
});

app.get('/api/posts/:id', (req, res) => {
    const post = posts.find(p => p.id == req.params.id);
    if (!post) return res.status(404).json({ error: 'Post not found' });
    res.json(post);
});

app.listen(3000, () => console.log('API running on port 3000'));

Error Handling

// Global error handler
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ error: 'Internal server error' });
});

Production Checklist

  • Version your API (/api/v1/)
  • Rate limit to prevent abuse
  • Validate all input data
  • Use HTTPS in production
  • Add authentication (JWT recommended)
  • Document with Swagger/OpenAPI
  • Log requests and errors

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top