HTTP

Guide

How HTTP Works: The Complete Guide

Learn how HTTP works with interactive examples. Understand requests, responses, methods, headers, status codes, and the complete request lifecycle in minutes.

11 min read beginner Try in Playground

TL;DR: HTTP is a request-response protocol where browsers send requests (GET, POST, etc.) to servers, which respond with status codes, headers, and content. HTTPS adds encryption for security.

HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the web. Every time you browse a website, check your email, or use a mobile app, HTTP is working behind the scenes to transfer information between your device and servers around the world.

This guide explains how HTTP works in plain language with practical examples you can try yourself.

What is HTTP?

HTTP is a set of rules (a protocol) that defines how messages are formatted and transmitted between web browsers and servers. Think of it as the language that your browser speaks to communicate with websites.

Key characteristics of HTTP:

  • Client-server model: Your browser (client) sends requests, servers send responses
  • Stateless: Each request is independent—the server doesn’t remember previous requests
  • Text-based: HTTP messages are human-readable (at least in HTTP/1.1)
  • Extensible: Headers allow adding new features without breaking existing systems

When you type https://example.com in your browser, HTTP handles the entire conversation between your browser and the web server.

The HTTP Request-Response Cycle

Every HTTP interaction follows a simple pattern: request and response.

Step 1: You Make a Request

When you click a link or type a URL, your browser creates an HTTP request:

GET /products/shoes HTTP/1.1
Host: shop.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: text/html,application/json
Accept-Language: en-US,en;q=0.9
```text

This request says: "Please send me the page at `/products/shoes` from `shop.example.com`."

### Step 2: The Server Responds

The server processes your request and sends back a response:

```http
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 4523
Cache-Control: max-age=3600

<!DOCTYPE html>
<html>
  <head><title>Shoes - Example Shop</title></head>
  <body>
    <h1>Our Shoe Collection</h1>
    <!-- Page content here -->
  </body>
</html>

The 200 OK status tells your browser the request succeeded, and the HTML content follows.

Step 3: Your Browser Renders the Page

Your browser receives the HTML, then makes additional HTTP requests for images, CSS files, JavaScript, and other resources needed to display the complete page.

Try it yourself → Use our interactive playground to see real HTTP requests and responses.

HTTP Methods: What Action to Take

HTTP methods (also called verbs) tell the server what action you want to perform. The most common methods are:

MethodPurposeHas Body?Safe?Idempotent?
GETRetrieve dataNoYesYes
POSTCreate new dataYesNoNo
PUTReplace existing dataYesNoYes
PATCHPartially update dataYesNoNo
DELETERemove dataOptionalNoYes
HEADGet headers onlyNoYesYes
OPTIONSCheck allowed methodsNoYesYes

GET: Retrieving Information

GET requests fetch data without changing anything on the server:

GET /api/users/123 HTTP/1.1
Host: api.example.com
Accept: application/json
```text

Response:

```http
HTTP/1.1 200 OK
Content-Type: application/json

{
  "id": 123,
  "name": "Alice Johnson",
  "email": "alice@example.com"
}

POST: Creating New Data

POST requests send data to create new resources:

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

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

Response:

```http
HTTP/1.1 201 Created
Location: /api/users/124
Content-Type: application/json

{
  "id": 124,
  "name": "Bob Smith",
  "email": "bob@example.com",
  "createdAt": "2026-01-19T10:30:00Z"
}

Try creating a resource → See POST in action with our playground.

HTTP Headers: Metadata About the Message

Headers provide additional information about the request or response. They’re key-value pairs that control caching, authentication, content negotiation, and more.

Common Request Headers

HeaderPurposeExample
HostTarget serverHost: api.example.com
User-AgentClient identificationUser-Agent: Mozilla/5.0...
AcceptPreferred response formatAccept: application/json
AuthorizationAuthentication credentialsAuthorization: Bearer token123
Content-TypeRequest body formatContent-Type: application/json
CookieSession dataCookie: session=abc123

Common Response Headers

HeaderPurposeExample
Content-TypeResponse body formatContent-Type: text/html
Content-LengthBody size in bytesContent-Length: 1234
Cache-ControlCaching instructionsCache-Control: max-age=3600
Set-CookieStore cookie on clientSet-Cookie: session=xyz
LocationRedirect URLLocation: /new-page

Example: Content Negotiation

Headers let clients and servers negotiate the best format:

GET /api/data HTTP/1.1
Host: api.example.com
Accept: application/json, text/xml;q=0.9, */*;q=0.8
Accept-Language: en-US,en;q=0.9,es;q=0.8
Accept-Encoding: gzip, deflate, br
```http

The server responds with the best match:

```http
HTTP/1.1 200 OK
Content-Type: application/json
Content-Language: en-US
Content-Encoding: gzip
Vary: Accept, Accept-Language, Accept-Encoding

HTTP Status Codes: What Happened?

Status codes are three-digit numbers that tell you the result of your request. They’re grouped into five categories:

1xx: Informational

The server received your request and is processing it.

2xx: Success

Your request was received, understood, and accepted.

3xx: Redirection

You need to take additional action to complete the request.

4xx: Client Errors

Something was wrong with your request.

5xx: Server Errors

The server failed to fulfill a valid request.

Explore all status codes → See detailed explanations and examples for every HTTP status code.

The Complete HTTP Lifecycle

When you request a webpage, here’s what happens step by step:

1. DNS Resolution (10-100ms)

Your browser converts the domain name to an IP address:

example.com → 93.184.216.34

2. TCP Connection (20-100ms)

Your browser establishes a connection using the TCP three-way handshake:

Client → Server: SYN
Server → Client: SYN-ACK
Client → Server: ACK

3. TLS Handshake (50-200ms)

For HTTPS, encryption is negotiated:

Client → Server: ClientHello (supported ciphers)
Server → Client: ServerHello + Certificate
Client → Server: Key exchange
Both: Derive encryption keys

4. HTTP Request (1-10ms)

Your browser sends the HTTP request over the encrypted connection.

5. Server Processing (10-1000ms)

The server:

  • Parses the request
  • Authenticates the user (if needed)
  • Retrieves data from databases
  • Generates the response

6. HTTP Response (1-50ms)

The server sends back the response with status code, headers, and body.

7. Rendering

Your browser parses HTML, requests additional resources (CSS, JS, images), and renders the page.

See the lifecycle animated → Watch the complete request-response cycle in action.

HTTP Versions: Evolution of the Protocol

HTTP/0.9 (1991)

The original version—extremely simple:

GET /page.html

Response was just the HTML content, no headers or status codes.

HTTP/1.0 (1996)

Added headers, status codes, and content types:

GET /page.html HTTP/1.0
User-Agent: NCSA_Mosaic/2.0

HTTP/1.0 200 OK
Content-Type: text/html
```javascript

### HTTP/1.1 (1997)

Still widely used today. Key improvements:

- **Persistent connections**: Reuse TCP connections for multiple requests
- **Chunked transfer**: Stream responses of unknown length
- **Host header**: Multiple websites on one IP address
- **Caching controls**: Fine-grained cache management

### HTTP/2 (2015)

Major performance improvements:

- **Multiplexing**: Multiple requests over one connection simultaneously
- **Header compression**: Reduces overhead with HPACK
- **Server push**: Send resources before they're requested
- **Binary framing**: More efficient than text-based HTTP/1.1

### HTTP/3 (2022)

Built on QUIC instead of TCP:

- **Faster connections**: 0-RTT connection establishment
- **Better mobile performance**: Handles network changes gracefully
- **Improved security**: TLS 1.3 built into the protocol
- **No head-of-line blocking**: Lost packets don't delay other streams

## HTTP vs HTTPS: Security Matters

HTTPS is HTTP with encryption. The "S" stands for Secure.

| Aspect          | HTTP            | HTTPS              |
| --------------- | --------------- | ------------------ |
| Port            | 80              | 443                |
| Encryption      | None            | TLS/SSL            |
| Data visibility | Anyone can read | Encrypted          |
| Authentication  | None            | Server certificate |
| SEO impact      | Penalized       | Preferred          |

### Why HTTPS Matters

1. **Privacy**: Prevents eavesdropping on sensitive data
2. **Integrity**: Ensures data isn't modified in transit
3. **Authentication**: Verifies you're talking to the real server
4. **Trust**: Browsers show security indicators
5. **SEO**: Google ranks HTTPS sites higher

Modern browsers mark HTTP sites as "Not Secure." Always use HTTPS for production websites.

## Cookies and Sessions: Maintaining State

HTTP is stateless, but cookies let servers remember users across requests.

### How Cookies Work

1. Server sends a cookie in the response:

```http
HTTP/1.1 200 OK
Set-Cookie: session_id=abc123; Path=/; HttpOnly; Secure; SameSite=Strict
  1. Browser stores the cookie and sends it with future requests:
GET /dashboard HTTP/1.1
Host: example.com
Cookie: session_id=abc123
```text

### Cookie Security Attributes

| Attribute                           | Purpose                          |
| ----------------------------------- | -------------------------------- |
| [HttpOnly](/cookies/http-only)      | Prevents JavaScript access       |
| [Secure](/cookies/secure)           | Only sent over HTTPS             |
| [SameSite](/cookies/same-site)      | Controls cross-site sending      |
| [Domain](/cookies/domain)           | Which domains receive the cookie |
| [Path](/cookies/path)               | Which paths receive the cookie   |
| [Expires/Max-Age](/cookies/expires) | When the cookie expires          |

**[Learn more about cookie security](/guides/cookie-security)**

## Caching: Making HTTP Faster

Caching stores responses to avoid redundant network requests.

### Cache-Control Header

```http
Cache-Control: max-age=3600, public

Common directives:

DirectiveMeaning
max-age=NCache for N seconds
no-cacheRevalidate before using
no-storeNever cache
publicAny cache can store
privateOnly browser can cache
immutableNever changes

Conditional Requests

Validate cached content without downloading again:

GET /styles.css HTTP/1.1
If-None-Match: "abc123"
If-Modified-Since: Fri, 18 Jan 2026 10:00:00 GMT
```text

If unchanged, server responds:

```http
HTTP/1.1 304 Not Modified

Deep dive into caching →

CORS: Cross-Origin Requests

By default, browsers block requests to different domains. CORS (Cross-Origin Resource Sharing) allows controlled cross-origin access.

Simple Request

GET /api/data HTTP/1.1
Host: api.example.com
Origin: https://mysite.com
```text

Server allows it:

```http
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://mysite.com

Preflight Request

For complex requests, browsers send an OPTIONS request first:

OPTIONS /api/data HTTP/1.1
Host: api.example.com
Origin: https://mysite.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type, Authorization
```http

Server responds with permissions:

```http
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://mysite.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400

Complete CORS guide →

Common HTTP Patterns

RESTful API Design

REST uses HTTP methods semantically:

GET    /users          # List all users
GET    /users/123      # Get user 123
POST   /users          # Create new user
PUT    /users/123      # Replace user 123
PATCH  /users/123      # Update user 123
DELETE /users/123      # Delete user 123
```text

### Pagination

```http
GET /api/posts?page=2&limit=20 HTTP/1.1

HTTP/1.1 200 OK
Link: </api/posts?page=1&limit=20>; rel="prev",
      </api/posts?page=3&limit=20>; rel="next"
X-Total-Count: 156

Authentication

Bearer Token:

GET /api/profile HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
```text

**Basic Auth:**

```http
GET /api/profile HTTP/1.1
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

Learn about HTTP authentication →

Debugging HTTP

Browser DevTools

  1. Open DevTools (F12 or Cmd+Option+I)
  2. Go to Network tab
  3. Reload the page
  4. Click any request to see details

curl Command Line

# Simple GET request
curl https://api.example.com/users

# See headers
curl -I https://api.example.com/users

# POST with JSON
curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice"}'

# Verbose output
curl -v https://api.example.com/users

Common Issues

ProblemLikely CauseSolution
404 Not FoundWrong URL or resource deletedCheck URL spelling
401 UnauthorizedMissing or invalid credentialsCheck authentication
403 ForbiddenInsufficient permissionsRequest access
500 Server ErrorServer-side bugCheck server logs
CORS errorMissing CORS headersConfigure server CORS
TimeoutSlow server or networkIncrease timeout, optimize server

Best Practices

For API Consumers

  1. Handle errors gracefully: Check status codes and display helpful messages
  2. Implement retries: Use exponential backoff for transient failures
  3. Cache responses: Respect Cache-Control headers
  4. Use compression: Send Accept-Encoding: gzip
  5. Set timeouts: Don’t wait forever for slow servers

For API Providers

  1. Use appropriate status codes: Don’t return 200 for errors
  2. Include helpful error messages: Tell clients what went wrong
  3. Implement rate limiting: Protect against abuse
  4. Enable CORS properly: Don’t use * in production
  5. Use HTTPS: Encrypt all traffic
  6. Version your API: Use /v1/ or headers for versioning

Try It Yourself

Ready to experiment with HTTP? Use our interactive tools:

Summary

HTTP is the protocol that powers the web. Understanding how it works helps you:

  • Build better web applications
  • Debug network issues faster
  • Optimize performance
  • Implement secure authentication
  • Design clean APIs

Key takeaways:

  1. HTTP follows a request-response model
  2. Methods define what action to take (GET, POST, PUT, DELETE)
  3. Headers carry metadata about messages
  4. Status codes indicate success or failure
  5. HTTPS encrypts HTTP for security
  6. Cookies maintain state across requests
  7. Caching improves performance

Interactive Checkpoints

Interactive Check

Choose the right request method

Your frontend needs to fetch a paginated list of products without creating or changing any data. Which request should it send?

Choose the right request method

Frequently Asked Questions

What does HTTP stand for?

HTTP stands for Hypertext Transfer Protocol. It's the protocol used to transfer data between web browsers and servers on the internet.

What is the difference between HTTP and HTTPS?

HTTPS is HTTP with encryption. HTTPS uses TLS/SSL to encrypt all data transmitted between the browser and server, preventing eavesdropping and tampering. HTTP sends data in plain text.

How does HTTP work in simple terms?

HTTP works like a conversation: your browser sends a request asking for something (like a webpage), and the server sends back a response with the content. Every request includes a method (GET, POST, etc.), headers with metadata, and sometimes a body with data.

What are the most common HTTP methods?

The most common HTTP methods are GET (retrieve data), POST (create data), PUT (replace data), PATCH (update data), and DELETE (remove data). GET and POST account for over 95% of web traffic.

What does a 404 error mean?

A 404 error means 'Not Found'—the server couldn't find the resource you requested. This usually happens when a page has been deleted, moved, or the URL was typed incorrectly.

Is HTTP secure?

No, standard HTTP is not secure. Data sent over HTTP can be intercepted and read by anyone on the network. Always use HTTPS for websites that handle sensitive information.

What is an HTTP header?

HTTP headers are key-value pairs that carry metadata about the request or response. They control caching, authentication, content type, cookies, and many other aspects of HTTP communication.

What is the difference between HTTP/1.1 and HTTP/2?

HTTP/2 is faster than HTTP/1.1 because it supports multiplexing (multiple requests over one connection), header compression, and server push. HTTP/1.1 requires separate connections for each request.

What causes a 500 Internal Server Error?

A 500 error means something went wrong on the server while processing your request. Common causes include bugs in server code, database connection failures, misconfigured servers, or running out of memory.

How long has HTTP been around?

HTTP was created by Tim Berners-Lee in 1991 as part of the World Wide Web project at CERN. Versions include HTTP/0.9, HTTP/1.0 (1996), HTTP/1.1 (1997), HTTP/2 (2015), and HTTP/3 (2022).

Keep Learning