Back to Interview PrepGet interview ready with AILearn each topic the way interviewers ask it, then answer like you would in the interview.

Networking

REST APIs

Overview

What is REST APIs?

A REST API (Representational State Transfer Application Programming Interface) is an architectural style for networked applications that utilizes standard web protocols, primarily HTTP. It enables communication between clients and servers, allowing for the exchange of data and performance of actions in a standardized, stateless manner.

Benefits of REST APIs

  • Scalable - Stateless requests make it easier to scale applications.
  • Platform Independent - Works with any client (web, mobile, desktop).
  • Simple to Use - Uses standard HTTP methods like GET, POST, PUT, DELETE.
  • Flexible Data Format - Usually uses JSON, which is lightweight and easy to parse.
  • Separation of Concerns - Frontend and backend can be developed independently.
  • Easy Integration - Can easily connect with third-party services and systems.

Architecture

1-Tier Architecture

1-Tier architecture: front and back everything at one place

In a 1-tier architecture, the frontend and backend live in the same place - everything at one place. There is no separation between the client and server layers.

2-Tier Architecture

2-Tier architecture: frontend and backend connected through an API/REST layer

In a 2-tier architecture, the frontend and backend are separated and communicate through an API/REST layer.

3-Tier Architecture

3-Tier architecture: frontend, backend and database as separate layers

A 3-tier architecture adds a third layer: the frontend talks to the backend through an API/REST layer, and the backend talks to a database to store and retrieve data.

Building Blocks

Request - Response

REST API request-response cycle: client sends request, server processes and fetches data, then returns a response

In the request-response cycle, a client sends an HTTP request to a server asking for data or an action to be performed.

The server processes the request and sends back an HTTP response, usually containing data (like JSON) or a status message.

HTTP Request

Anatomy of an HTTP request: request line, request headers, request body

An HTTP request is sent by a client (browser) to a server to request a resource such as a webpage, CSS file, or API data. It mainly contains three parts:

  • Request Line - Includes the HTTP method, URL, and HTTP version (e.g., GET /styles.css HTTP/1.1).
  • Request Headers - Provide metadata about the request like Host, User-Agent, Accept, Accept-Language, Connection, etc.
  • Request Body - Optional data sent with the request (usually used in POST, PUT, PATCH requests). For GET requests, the body is typically empty.

HTTP Response

Anatomy of an HTTP response: status line, response headers, response body

An HTTP response is sent by the server back to the client after processing an HTTP request. It mainly contains three parts:

  • Status Line - Includes the HTTP version, status code, and status message (e.g., HTTP/1.1 200 OK), which indicates whether the request was successful or failed.
  • Response Headers - Provide metadata about the response such as Date, Content-Type, Content-Length, Accept-Ranges, etc.
  • Response Body - Contains the actual data returned by the server, such as HTML, CSS, JSON, or other resources (e.g., CSS code like nav.navbar { ... }).

Creating an Express Server

1. Create a project folder

mkdir express-server
cd express-server

2. Initialize a Node.js project

npm init -y

This creates a package.json file for the project.

3. Install Express

npm install express

4. Create the server file - create a file named:

server.js

5. Import Express

const express = require("express");

6. Create an Express application

const app = express();

7. Create a route

app.get("/", (req, res) => {
  res.send("Hello from Express Server");
});

8. Start the server

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

9. Run the server

node server.js

Open in browser:

http://localhost:3000

You will see:

Browser showing Hello from Express Server at localhost:3000

URL

Anatomy of a URL: scheme, subdomain, domain, TLD, host, path, query string, parameters, fragment
  1. Scheme (Protocol) https:// - Defines the protocol used to communicate with the server. Common protocols: HTTP, HTTPS, FTP.
  2. Subdomain www - A subdivision of the main domain used to organize sections of a website.
  3. Domain example - The main name of the website that identifies it on the internet.
  4. Top Level Domain (TLD) .com - The last part of the domain name. Examples: .com, .org, .net, .edu.
  5. Host www.example.com - The complete domain name (subdomain + domain + TLD) that points to the server.
  6. Path /forum/questions - Specifies the exact resource or page on the server.
  7. Query String ?tag=networking&order=newest - Contains parameters sent to the server to filter or modify the response.
  8. Parameters (Key-Value pairs) tag = networking, order = newest - These are used by the server to process the request dynamically.
  9. Fragment #top - Points to a specific section inside the webpage.

Note: The fragment (#...) is never sent to the server. It is handled entirely by the browser to navigate within the page, so the server has no knowledge of it.

Creating a TODO Application

Routes

  • POST /todo → Create a new todo
  • GET /users → Get all users

Features (CRUD)

  • Create Todo → Add a new todo
  • View Todo → Read existing todos
  • Edit Todo → Update a todo
  • Delete Todo → Remove a todo

These operations form CRUD:

  • C → Create
  • R → Read
  • U → Update
  • D → Delete

HTTP Methods Used

  • POST → Create a new resource
  • GET → Retrieve data
  • PUT → Update an entire resource
  • PATCH → Partially update a resource
  • DELETE → Remove a resource

Other HTTP Methods

  • HEAD → Same as GET but returns only headers (no body)
  • OPTIONS → Shows allowed HTTP methods for a resource
  • CONNECT → Establishes a network tunnel (used in proxies)
  • TRACE → Returns the request for debugging purposes

In-Memory TODO API (Express)

1. Setup Express

npm init -y
npm install express

Create server.js:

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

let todos = [
  { id: 1, task: "Learn Express", completed: false },
  { id: 2, task: "Build REST API", completed: false }
];

2. GET → Read Todos

app.get("/todos", (req, res) => {
  res.json(todos);
});

Get single todo:

app.get("/todos/:id", (req, res) => {
  const todo = todos.find(t => t.id === parseInt(req.params.id));
  res.json(todo);
});

3. POST → Create Todo

app.post("/todos", (req, res) => {
  const newTodo = {
    id: Date.now(),
    task: req.body.task,
    completed: false
  };
  todos.push(newTodo);
  res.status(201).json(newTodo);
});

Example request body:

{
  "task": "Study REST APIs"
}

4. PUT → Update Entire Todo

app.put("/todos/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const index = todos.findIndex(t => t.id === id);

  todos[index] = {
    id,
    task: req.body.task,
    completed: req.body.completed
  };

  res.json(todos[index]);
});

PUT replaces the whole resource.

5. PATCH → Partial Update

app.patch("/todos/:id", (req, res) => {
  const todo = todos.find(t => t.id === parseInt(req.params.id));

  if (req.body.task !== undefined) {
    todo.task = req.body.task;
  }
  if (req.body.completed !== undefined) {
    todo.completed = req.body.completed;
  }

  res.json(todo);
});

PATCH updates only specific fields.

6. DELETE → Remove Todo

app.delete("/todos/:id", (req, res) => {
  const id = parseInt(req.params.id);
  todos = todos.filter(t => t.id !== id);
  res.json({ message: "Todo deleted" });
});

7. HEAD Method

Returns headers only (no body).

app.head("/todos", (req, res) => {
  res.status(200).end();
});

8. OPTIONS Method

Shows allowed HTTP methods.

app.options("/todos", (req, res) => {
  res.set("Allow", "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS");
  res.send();
});

9. TRACE Method (rarely used)

app.trace("/trace", (req, res) => {
  res.send(req.headers);
});

10. Start Server

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

Example API Endpoints

GET     /todos
GET     /todos/:id
POST    /todos
PUT     /todos/:id
PATCH   /todos/:id
DELETE  /todos/:id
HEAD    /todos
OPTIONS /todos
TRACE   /trace

Headers

Request Headers

HeaderUse CaseExample
HostSpecifies the target server/domain where the request is sentHost: www.example.com
OriginIndicates the origin of the request (used in CORS validation)Origin: https://example.com
RefererShows the previous webpage from which the request was madeReferer: https://example.com/previous-page
User-AgentIdentifies the client making the request (browser, OS, device)User-Agent: Mozilla/5.0 Chrome/119
AcceptSpecifies the response content type the client expectsAccept: application/json
Accept-LanguageIndicates the preferred language for the responseAccept-Language: en-US,en;q=0.9
Accept-EncodingLists the compression formats supported by the clientAccept-Encoding: gzip, deflate, br
ConnectionControls whether the TCP connection stays open or closesConnection: keep-alive
AuthorizationSends authentication credentials (token, API key, etc.)Authorization: Bearer <token>
CookieSends stored cookies from the browser to the serverCookie: sessionId=abc123
If-Modified-SinceUsed for cache validation; server returns data only if modified after the given dateIf-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT
Cache-ControlDefines caching behavior for the requestCache-Control: no-cache

Response Headers

HeaderUse CaseExample
Content-TypeSpecifies the format of the response bodyContent-Type: application/json
Content-LengthIndicates the size of the response body in bytesContent-Length: 348
DateThe date and time when the response was generatedDate: Tue, 15 Nov 2026 08:12:31 GMT
ServerIdentifies the software used by the serverServer: nginx/1.24.0
Set-CookieSends cookies from the server to be stored by the clientSet-Cookie: sessionId=abc123; HttpOnly
Cache-ControlDefines caching rules for the responseCache-Control: max-age=3600
ETagA unique identifier for a specific version of a resource (used for caching)ETag: "abc123xyz"
Last-ModifiedShows the last time the resource was modifiedLast-Modified: Wed, 21 Oct 2015 07:28:00 GMT
LocationRedirects the client to another URLLocation: https://example.com/new-page
Access-Control-Allow-OriginDefines which origins are allowed to access the resource (CORS)Access-Control-Allow-Origin: *
Content-EncodingIndicates the compression used in the responseContent-Encoding: gzip
ConnectionControls whether the network connection stays open or closesConnection: keep-alive

HTTP Status Codes

1xx — Informational

CodeMeaningDescription
100ContinueRequest received, client should continue sending body
101Switching ProtocolsServer switching protocols (e.g., HTTP → WebSocket)
102ProcessingServer has received request and is processing

2xx — Success

CodeMeaningDescription
200OKRequest succeeded
201CreatedResource successfully created
202AcceptedRequest accepted but processing not complete
204No ContentSuccess but no response body

3xx — Redirection

CodeMeaningDescription
301Moved PermanentlyResource permanently moved
302FoundTemporary redirect
303See OtherRedirect to another resource
304Not ModifiedResource not modified (cache)
307Temporary RedirectSame request method but temporary redirect
308Permanent RedirectPermanent redirect with same method

4xx — Client Errors

CodeMeaningDescription
400Bad RequestInvalid request syntax
401UnauthorizedAuthentication required
403ForbiddenServer refuses request
404Not FoundResource not found
405Method Not AllowedHTTP method not supported
408Request TimeoutServer timed out waiting
409ConflictRequest conflicts with current state
413Payload Too LargeRequest body too large
415Unsupported Media TypeUnsupported content type
429Too Many RequestsRate limit exceeded

5xx — Server Errors

CodeMeaningDescription
500Internal Server ErrorGeneric server failure
501Not ImplementedServer doesn't support functionality
502Bad GatewayInvalid response from upstream server
503Service UnavailableServer temporarily unavailable
504Gateway TimeoutUpstream server timeout
You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in