HVRDHVRD
Protocols

HTTP

Comprehensive theoretical and practical documentation covering HTTP Servers, Protocol Constructs, and related concepts.

HTTP Servers

An HTTP Server is a program that listens for HTTP requests from clients (e.g., web browsers) and responds with HTTP responses. These servers form the backbone of the web by serving web pages, APIs, files, and other resources.

Purpose of HTTP Servers

HTTP servers abstract away low-level networking details and provide a structured, reliable way to serve content over the network. They handle:

  • Parsing HTTP requests
  • Routing requests based on URLs
  • Handling headers, methods, and body content
  • Sending appropriate HTTP responses

Popular implementations include Apache, Nginx, and in the Node.js ecosystem, servers built using the built-in http module or frameworks like Express.js.


Introduction to the HTTP Protocol

What Does HTTP Solve?

HTTP (HyperText Transfer Protocol) is designed to standardize how clients and servers communicate over TCP/IP networks. Without HTTP, communication would require bespoke protocols for each interaction, leading to interoperability issues.

HTTP provides a universal, stateless, request-response communication model that ensures clients and servers can interact without maintaining connection state.

a. Exploring the Network Tab in Chrome Developer Tools

The Network tab in Chrome Developer Tools shows each HTTP request and response for a web page load. It includes:

  • URL
  • HTTP Method (GET, POST, etc.)
  • Status Code (e.g., 200 OK)
  • Request Headers (User-Agent, Authorization, etc.)
  • Response Headers (Content-Type, Cache-Control, etc.)
  • Payload (body of request/response)
  • Timing information (latency, download time)

This is invaluable for debugging and understanding actual network traffic.

b. Request-Response Model

The HTTP communication flow:

  1. Client makes a request:

    • Sends HTTP Method (GET, POST, etc.)
    • Specifies URL (e.g., /api/todos)
    • Provides headers and optionally a body.
  2. Server processes the request:

    • Parses method, headers, body.
    • Matches the URL against defined routes.
    • Executes appropriate logic.
  3. Server sends a response:

    • Status code (200, 404, 500, etc.)
    • Response headers (Content-Type, etc.)
    • Body (HTML, JSON, plaintext).

HTTP is stateless: each request is independent, and no session state is preserved unless explicitly managed (via cookies, tokens, etc.).


Diving into HTTP Constructs

Domain Name and IP Address

  • Domain Name: A human-readable address (e.g., example.com).
  • IP Address: A machine-readable numeric address (e.g., 93.184.216.34).
  • DNS (Domain Name System) maps domain names to IP addresses, allowing easy access without memorizing numbers.

Detailed Flow

When you type example.com in your browser:

  1. Browser asks the OS for the IP address of example.com.
  2. OS checks local DNS cache; if not found, queries DNS servers.
  3. DNS returns the IP address 93.184.216.34.
  4. Browser opens a TCP connection to 93.184.216.34.

Port

A Port is a numeric identifier (16-bit integer) that specifies a communication endpoint on a machine. It distinguishes multiple services running on the same machine.

  • Range: 0 – 65535
    • Ports 0–1023: Well-known ports (e.g., 80 for HTTP, 443 for HTTPS).
    • Ports 1024–49151: Registered ports.
    • Ports 49152–65535: Dynamic/private ports.

Example:
Accessing http://example.com:8080/ means connecting to IP 93.184.216.34 at port 8080.

Ports enable multiplexing multiple services on a single machine.

Why Ports Matter

Without ports, only one service could listen on a machine at a time. Ports solve this by providing multiple endpoints.
Example services:

ServiceDefault Port
HTTP80
HTTPS443
FTP21
SSH22
MySQL3306

HTTP Methods

Each method serves a specific purpose:

  • GET: Retrieve data without modifying state.
  • POST: Send data to create a resource.
  • PUT: Replace an existing resource.
  • PATCH: Partially modify a resource.
  • DELETE: Remove a resource.
  • OPTIONS: Describe available communication options.
  • HEAD: Same as GET but returns headers only (no body).

Example of a GET Request

GET /api/todos HTTP/1.1
Host: example.com

Response Formats

  1. Plaintext

    • Simple text responses.
    • Example Header: Content-Type: text/plain
    • Example Body: Hello, world!
  2. JSON (JavaScript Object Notation)

    • Structured data format widely used for APIs.
    • Example Header: Content-Type: application/json
    • Example Body:
    { "id": 1, "task": "Learn HTTP" }
  3. HTML (HyperText Markup Language)

    • Standard format for web pages.
    • Example Header: Content-Type: text/html
    • Example Body:
    <html><body><h1>Welcome</h1></body></html>

Status Codes

CodeDescription
200OK – Successful response
201Created – Resource successfully created
400Bad Request – Client error
401Unauthorized – Authentication required
403Forbidden – Permission denied
404Not Found – Resource not found
500Internal Server Error – Server failed to process request

Example Status Line

HTTP/1.1 200 OK

Body and Headers

  • Headers: Key-value metadata for request/response.

    • Examples:
      • Content-Type: application/json
      • Authorization: Bearer abc123
  • Body: Actual data transmitted (for POST, PUT requests and responses).

Example POST Request Body:

{
  "task": "Build HTTP Server"
}

Routes

A route maps a URL path and HTTP method to a specific handler in the server code.

Example using Node.js http module:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/api/todos' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify([{ id: 1, task: 'Learn HTTP' }]));
    return;
  }

  res.writeHead(404, { 'Content-Type': 'text/plain' });
  res.end('Not Found');
});

server.listen(3000);

Installing and Using Postman

Postman is a GUI tool used for sending HTTP requests and viewing responses without writing code.

Features

  • Send custom HTTP methods (GET, POST, PUT, etc.).
  • Manage request headers and bodies.
  • Save requests for later.
  • View detailed response with headers, body, and status codes.

Installation

Download from: https://www.postman.com/downloads/

Example Usage

  1. Open Postman → Create new request.
  2. Set method (e.g., POST) and URL (e.g., http://localhost:3000/api/todos).
  3. Add headers (e.g., Content-Type: application/json).
  4. Add body (raw JSON):
{ "task": "Learn Postman" }
  1. Send request and view response.

Example In-Memory Todo Application

An HTTP server to store todos in memory.

const http = require('http');

let todos = [];

const server = http.createServer((req, res) => {
  if (req.url === '/todos' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(todos));
    return;
  }

  if (req.url === '/todos' && req.method === 'POST') {
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      const { task } = JSON.parse(body);
      const newTodo = { id: todos.length + 1, task };
      todos.push(newTodo);

      res.writeHead(201, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(newTodo));
    });
    return;
  }

  res.writeHead(404, { 'Content-Type': 'text/plain' });
  res.end('Not Found');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});