Skip to main content

Understanding HTTP Communication

HTTP (HyperText Transfer Protocol) is the foundation of data exchange on the web. It defines how messages are formatted and transmitted between clients (browsers, applications) and servers. This guide explains how HTTP communication works, the structure of requests and responses, and the meaning of different status codes.

What is HTTP?

HTTP is a stateless, request-response protocol. This means:

  • Stateless: Each request is independent. The server doesn't maintain information about previous requests from a client unless explicitly told to (via cookies or sessions)
  • Request-Response: Communication always begins with a client sending a request, and the server responding with a response
  • Text-based: All HTTP messages are human-readable text, making them easy to debug
  • Connection-based: HTTP typically uses TCP connections (port 80 for HTTP, port 443 for HTTPS)

How HTTP Communication Works

When you interact with a website or API, the following sequence occurs:

  1. Client initiates: Your browser or application sends an HTTP request to a server
  2. Server receives: The server reads and processes the request
  3. Server responds: The server sends back an HTTP response with the requested data or an error message
  4. Client processes: Your browser or application processes the response and takes appropriate action (display a webpage, save data, show an error, etc.)
  5. Connection closes: The TCP connection closes (or is reused for subsequent requests with HTTP/1.1 keep-alive)

This entire cycle typically takes 100-500ms depending on network conditions and server processing time.

HTTP Requests

An HTTP request is a message sent by a client to a server, asking for an action or resource.

Structure of an HTTP Request

Every HTTP request consists of three parts:

[Request Line]
[Headers]
[Blank Line]
[Body (optional)]

Request Line

The first line of an HTTP request contains three components:

METHOD /path/to/resource HTTP/1.1
  • METHOD: The HTTP verb indicating the action (GET, POST, PUT, DELETE, etc.)
  • Path: The resource being requested (e.g., /index.html, /api/users, /search?q=example)
  • HTTP Version: Usually HTTP/1.1 or HTTP/2

Example:

GET /index.html HTTP/1.1
POST /api/users HTTP/1.1

Headers

Headers are key-value pairs that provide metadata about the request. They come after the request line and before the body.

Common request headers:

HeaderPurposeExample
HostDomain name of the serverHost: example.com
User-AgentInformation about the clientUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Content-TypeFormat of the request bodyContent-Type: application/json
Content-LengthSize of the request body in bytesContent-Length: 256
AuthorizationCredentials for authenticationAuthorization: Bearer token123
AcceptData formats the client can handleAccept: application/json, text/html
Accept-LanguagePreferred languagesAccept-Language: en-US, en;q=0.9
RefererURL of the page that triggered the requestReferer: https://example.com/search
CookieSession or user identification dataCookie: sessionid=abc123; userid=42

Request Body

The body contains data being sent to the server. It's optional and typically used with POST, PUT, PATCH requests.

Examples:

JSON body (API request):

{
  "username": "john_doe",
  "email": "john@example.com",
  "password": "secure_password"
}

Form data (HTML form):

username=john_doe&email=john@example.com&subscribe=yes

Plain text:

This is a simple text message

Complete Request Example

POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Content-Length: 47
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

{
  "username": "alice",
  "email": "alice@example.com"
}

HTTP Request Methods

The HTTP method (verb) indicates the action you want to perform on a resource. The main methods are:

GET

Purpose: Retrieve data from a server. Should not modify data.

  • Body: Usually none
  • Safe: Yes (doesn't change server state)
  • Idempotent: Yes (same request produces same result)
  • Cacheable: Yes

Example:

GET /api/users/123 HTTP/1.1
Host: api.example.com

Use when: Fetching a webpage, retrieving data from an API, loading an image.

POST

Purpose: Submit data to create a new resource.

  • Body: Usually contains data (JSON, form data, etc.)
  • Safe: No (creates new data on server)
  • Idempotent: No (multiple requests create multiple resources)
  • Cacheable: No (unless explicitly specified)

Example:

POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
  "name": "Bob",
  "email": "bob@example.com"
}

Use when: Submitting a form, creating a new user account, uploading a file.

PUT

Purpose: Replace an entire resource with new data.

  • Body: Contains the complete updated resource
  • Safe: No
  • Idempotent: Yes (multiple identical requests have the same effect as one)
  • Cacheable: No

Example:

PUT /api/users/123 HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
  "name": "Bob Updated",
  "email": "bob.new@example.com",
  "role": "admin"
}

Use when: Completely replacing a resource (user profile, product details, etc.).

PATCH

Purpose: Partially update a resource (update only specified fields).

  • Body: Contains only the fields to be updated
  • Safe: No
  • Idempotent: Yes (usually, depending on implementation)
  • Cacheable: No

Example:

PATCH /api/users/123 HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
  "email": "bob.new@example.com"
}

Use when: Updating specific fields without replacing the entire resource.

DELETE

Purpose: Remove a resource from the server.

  • Body: Usually none
  • Safe: No (deletes data)
  • Idempotent: Yes (deleting the same resource multiple times is the same as deleting it once)
  • Cacheable: No

Example:

DELETE /api/users/123 HTTP/1.1
Host: api.example.com

Use when: Deleting a user account, removing a post, etc.

HEAD

Purpose: Same as GET, but the server returns only headers without the response body.

  • Body: None
  • Safe: Yes
  • Idempotent: Yes
  • Cacheable: Yes

Example:

HEAD /index.html HTTP/1.1
Host: example.com

Use when: Checking if a resource exists, getting metadata without downloading the full content.

OPTIONS

Purpose: Describe communication options available for the resource (used mainly for CORS).

  • Body: None
  • Safe: Yes
  • Idempotent: Yes

Example:

OPTIONS /api/users HTTP/1.1
Host: api.example.com

Server response includes allowed methods:

Allow: GET, POST, PUT, DELETE, OPTIONS

Use when: Checking what methods are allowed on a resource, CORS preflight requests.

HTTP Responses

An HTTP response is a message sent by the server back to the client after processing a request.

Structure of an HTTP Response

Every HTTP response consists of three parts:

[Status Line]
[Headers]
[Blank Line]
[Body (optional)]

Status Line

The first line indicates the outcome of the request:

HTTP/1.1 200 OK
  • HTTP Version: HTTP/1.1 or HTTP/2
  • Status Code: Three-digit number (200, 404, 500, etc.)
  • Reason Phrase: Human-readable description of the status

Response Headers

Headers provide metadata about the response.

Common response headers:

HeaderPurposeExample
Content-TypeFormat of the response bodyContent-Type: application/json; charset=utf-8
Content-LengthSize of response body in bytesContent-Length: 1024
Content-EncodingCompression appliedContent-Encoding: gzip
Cache-ControlCaching instructions for browsersCache-Control: max-age=3600
Set-CookieCreate/update a cookie on clientSet-Cookie: sessionid=abc123; Path=/
LocationURL for redirectsLocation: https://example.com/new-page
ServerIdentifies the web serverServer: nginx/1.21.0
Access-Control-Allow-OriginCORS - allowed originAccess-Control-Allow-Origin: *
ExpiresWhen the response expiresExpires: Wed, 21 Oct 2025 07:28:00 GMT
Last-ModifiedWhen resource was last modifiedLast-Modified: Mon, 15 Oct 2024 12:00:00 GMT

Response Body

The body contains the actual data being sent back (HTML, JSON, images, files, etc.). It's optional for some response types.

Complete Response Example

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 89
Cache-Control: max-age=3600
Set-Cookie: sessionid=xyz789; Path=/; HttpOnly

{
  "id": 123,
  "username": "alice",
  "email": "alice@example.com",
  "created_at": "2024-01-15T10:30:00Z"
}

HTTP Status Codes

Status codes tell the client whether the request succeeded, failed, or needs further action. They're grouped into five categories:

1xx - Informational

These are provisional responses; the request is being processed.

CodeMeaningUse Case
100 ContinueServer received headers, ready for bodyRare; used with large uploads
101 Switching ProtocolsProtocol upgrade (HTTP to WebSocket)WebSocket connections

2xx - Success

The request succeeded.

CodeMeaningUse Case
200 OKRequest successful, response contains dataGET, POST, PUT, PATCH requests that succeed
201 CreatedResource successfully createdPOST requests that create new resources
202 AcceptedRequest accepted for processing (async)Long-running tasks, background jobs
204 No ContentRequest succeeded, no response bodyDELETE requests, form submissions that don't return data
206 Partial ContentOnly part of resource returnedResume downloads, range requests

3xx - Redirection

The client must take further action to complete the request.

CodeMeaningUse Case
300 Multiple ChoicesMultiple options availableRare; user selects which resource
301 Moved PermanentlyResource moved to new URL (permanent)Site restructuring, old URLs should update bookmarks
302 FoundResource temporarily at different URLTemporary redirects, login redirects
304 Not ModifiedResource unchanged since last requestBrowser cache validation
307 Temporary RedirectTemporary redirect (preserves method)Like 302 but maintains POST as POST
308 Permanent RedirectPermanent redirect (preserves method)Like 301 but maintains POST as POST

Example: When you request http://example.com/old-page, server responds:

HTTP/1.1 301 Moved Permanently
Location: http://example.com/new-page

Your browser automatically follows to the new location.

4xx - Client Error

The request was malformed or cannot be fulfilled by the server.

CodeMeaningCause
400 Bad RequestRequest syntax is invalidMalformed JSON, invalid parameters
401 UnauthorizedAuthentication required or failedMissing or invalid API key, expired session
403 ForbiddenAuthenticated but not authorizedUser lacks permission to access resource
404 Not FoundResource doesn't existTypo in URL, deleted resource
405 Method Not AllowedHTTP method not supported for resourceUsing POST on a read-only endpoint
409 ConflictRequest conflicts with current stateDuplicate entry, version mismatch
410 GoneResource permanently deletedResource will not return
413 Payload Too LargeRequest body exceeds server limitUploading file larger than allowed
415 Unsupported Media TypeWrong Content-Type headerSending XML when API expects JSON
429 Too Many RequestsRate limit exceededToo many API calls in short time

5xx - Server Error

The server failed to fulfill a valid request.

CodeMeaningCause
500 Internal Server ErrorServer encountered unexpected errorUnhandled exception, database crash
501 Not ImplementedFunctionality not yet implementedFeature under development
502 Bad GatewayInvalid response from upstream serverMisconfigured proxy, backend unavailable
503 Service UnavailableServer temporarily unable to handle requestsMaintenance, overloaded, deployment
504 Gateway TimeoutUpstream server didn't respond in timeBackend is slow or unresponsive

Practical Examples

Example 1: Fetching a Webpage

Request:

GET /index.html HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: text/html,application/xhtml+xml
Accept-Language: en-US,en;q=0.9

Response:

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 1234
Cache-Control: public, max-age=3600

<!DOCTYPE html>
<html>
<head>
  <title>Example Domain</title>
</head>
<body>
  <h1>Example Domain</h1>
  <p>This domain is established to be used for examples in documents.</p>
</body>
</html>

Example 2: Creating a Resource via API

Request:

POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Content-Length: 47

{
  "name": "John Doe",
  "email": "john@example.com"
}

Success Response (201):

HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/users/456
Content-Length: 95

{
  "id": 456,
  "name": "John Doe",
  "email": "john@example.com",
  "created_at": "2024-03-22T14:30:00Z"
}

Error Response (400):

HTTP/1.1 400 Bad Request
Content-Type: application/json
Content-Length: 82

{
  "error": "Invalid email format",
  "field": "email",
  "message": "john@example is not a valid email address"
}

Example 3: Authentication Failure

Request:

GET /api/private/data HTTP/1.1
Host: api.example.com

Error Response (401):

HTTP/1.1 401 Unauthorized
Content-Type: application/json
WWW-Authenticate: Bearer realm="api"
Content-Length: 64

{
  "error": "Unauthorized",
  "message": "Authentication token is missing or invalid"
}

Example 4: Resource Not Found

Request:

GET /api/users/999 HTTP/1.1
Host: api.example.com

Error Response (404):

HTTP/1.1 404 Not Found
Content-Type: application/json
Content-Length: 56

{
  "error": "Not Found",
  "message": "User with ID 999 does not exist"
}

Example 5: Redirect

Request:

GET /old-location HTTP/1.1
Host: example.com

Response (301):

HTTP/1.1 301 Moved Permanently
Location: /new-location
Content-Length: 0

Browser automatically follows to /new-location.

Common Error Scenarios & Causes

ScenarioStatus CodeRoot Cause
User forgets API key401Missing Authorization header
User accesses account they don't own403Has auth but lacks permission
User requests deleted data404Resource no longer exists
User sends 10MB file to API limited to 5MB413Payload exceeds limit
User makes 1000 requests/minute to rate-limited API429Too many requests
Database suddenly crashes500Server error, not client's fault
Server restarting during deployment503Service temporarily unavailable
Firewall blocks connection to database502Upstream server unreachable

Summary

HTTP communication is straightforward:

  1. Client sends Request (method + headers + optional body)
  2. Server processes Request (validates, checks auth, accesses data)
  3. Server sends Response (status code + headers + optional body)
  4. Client processes Response (displays data, shows error, saves cookies, etc.)

Understanding requests and responses—their structure, methods, and status codes—is essential for:

  • Building and consuming APIs
  • Debugging web applications
  • Understanding browser behavior
  • Designing web services
  • Troubleshooting connectivity issues

Each component serves a purpose: methods indicate intent, headers provide context, bodies carry data, and status codes communicate outcomes.