Labs ICT
Pro Login

What is a REST API? How to Design One

General Concepts Explained 7 min read

REST APIs are the backbone of modern web apps. Learn REST principles, HTTP methods, and how to build your own API.

What is a REST API? How to Design One

REST APIs are the backbone of modern web applications. They let different systems communicate over HTTP. If you're building web apps, understanding REST is essential.

What is REST?

REST (Representational State Transfer) is an architectural style for designing networked applications. It uses standard HTTP methods and URLs to access and manipulate resources.

REST API Principles

  • Stateless — Each request contains all information needed
  • Client-Server — Client and server are separate
  • Uniform Interface — Consistent URL structure
  • Resource-Based — Everything is a resource with a URL

REST API Endpoints

Each resource has a URL. Here's a typical pattern for a blog:

GET    /articles          → List all articles
GET    /articles/1        → Get article with ID 1
POST   /articles          → Create a new article
PUT    /articles/1        → Update article with ID 1
DELETE /articles/1        → Delete article with ID 1

HTTP Methods

Method Purpose Example
GET Read data Fetch a list of users
POST Create data Add a new user
PUT Update data Edit user profile
DELETE Remove data Delete a user

Building a REST API with Express

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

let articles = [
  { id: 1, title: 'First Post', content: 'Hello World' }
];

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

// GET one article
app.get('/articles/:id', (req, res) => {
  const article = articles.find(a => a.id === parseInt(req.params.id));
  if (!article) return res.status(404).json({ error: 'Not found' });
  res.json(article);
});

// POST new article
app.post('/articles', (req, res) => {
  const article = {
    id: articles.length + 1,
    title: req.body.title,
    content: req.body.content
  };
  articles.push(article);
  res.status(201).json(article);
});

app.listen(3000);

Response Status Codes

  • 200 — Success
  • 201 — Created
  • 400 — Bad request
  • 404 — Not found
  • 500 — Server error

Note: REST APIs are simple to understand but powerful. Start with basic CRUD operations, then add authentication, pagination, and error handling as you advance.