networking30 min

REST APIs

Designing web APIs using REST principles

0/9Not Started

Why This Matters

Almost every modern application — mobile apps, single-page web apps, IoT devices — talks to a server through an API. The dominant style for designing those APIs is REST (Representational State Transfer). REST gives you a consistent, predictable way to organize your endpoints around resources and CRUD operations.

When you fetch data from Twitter, post a photo to Instagram, or check the weather on your phone, you are using a REST API. Learning REST means you can build backends that other developers (and your own frontend) can consume easily.

Define Terms

Visual Model

/users
/users/123
/users/123/posts
GETRead
POSTCreate
PUTUpdate
DELETERemove
/:id
/posts

The full process at a glance. Click Start tour to walk through each step.

REST maps CRUD operations to HTTP methods: GET (Read), POST (Create), PUT/PATCH (Update), DELETE (Delete).

Code Example

Code
// Consuming a REST API with fetch
const BASE_URL = "https://api.example.com";

// CREATE — POST /users
async function createUser(name, email) {
  const res = await fetch(`${BASE_URL}/users`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name, email })
  });
  return res.json(); // { id: 1, name: "Alice", email: "alice@ex.com" }
}

// READ — GET /users and GET /users/:id
async function getUsers() {
  const res = await fetch(`${BASE_URL}/users`);
  return res.json(); // [{ id: 1, ... }, { id: 2, ... }]
}

async function getUser(id) {
  const res = await fetch(`${BASE_URL}/users/${id}`);
  if (res.status === 404) throw new Error("User not found");
  return res.json(); // { id: 1, name: "Alice", ... }
}

// UPDATE — PUT /users/:id
async function updateUser(id, data) {
  const res = await fetch(`${BASE_URL}/users/${id}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data)
  });
  return res.json();
}

// DELETE — DELETE /users/:id
async function deleteUser(id) {
  const res = await fetch(`${BASE_URL}/users/${id}`, {
    method: "DELETE"
  });
  return res.status === 204; // true if deleted
}

// URL design best practices:
// GET    /users          — list all users
// GET    /users/1        — get user 1
// POST   /users          — create a user
// PUT    /users/1        — replace user 1
// PATCH  /users/1        — partial update user 1
// DELETE /users/1        — delete user 1
// GET    /users/1/posts  — list posts by user 1

Interactive Experiment

Try these exercises:

  • Open your browser dev tools and navigate to any website. Look at the Network tab. How many requests use GET? Do you see any POST requests?
  • Use the browser console to call a public REST API: fetch("https://jsonplaceholder.typicode.com/users/1").then(r => r.json()).then(console.log). Inspect the JSON response.
  • Try creating a fake post: fetch("https://jsonplaceholder.typicode.com/posts", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({title: "Hello", body: "World", userId: 1}) }).then(r => r.json()).then(console.log)
  • Design the REST endpoints for a blog: what URLs would you use for listing posts, creating a post, updating a post, and deleting a post?

Quick Quiz

Coding Challenge

REST URL Generator

Write a function called `generateEndpoint` that takes a resource name (string), an action ('list', 'get', 'create', 'update', or 'delete'), and an optional ID (number). Return an object with `method` (HTTP method) and `path` (URL path). Examples: ('users', 'list') returns { method: 'GET', path: '/users' }. ('users', 'get', 5) returns { method: 'GET', path: '/users/5' }.

Loading editor...

Real-World Usage

REST APIs are the backbone of modern software architecture:

  • Frontend-backend communication: React, Vue, and Angular apps fetch data from REST APIs. Mobile apps (iOS, Android) use the same API endpoints as the web.
  • Third-party integrations: Stripe (payments), Twilio (SMS), GitHub (code), and thousands of SaaS products expose REST APIs. Developers integrate them into their apps.
  • Microservices: In a microservice architecture, each service exposes a REST API. The user service, order service, and payment service all communicate via HTTP.
  • API versioning: Companies version their APIs (/v1/users, /v2/users) to make changes without breaking existing clients.
  • Pagination and filtering: Large collections use query parameters: GET /users?page=2&limit=20&sort=name. This keeps responses fast even with millions of records.
  • Alternatives to REST: GraphQL (query language for APIs), gRPC (binary protocol for microservices), and WebSockets (real-time bidirectional) solve problems REST handles less well.

Connections