1.3: HTTP and Web Communication
Understand the HTTP protocol that powers web communication, including request/response cycles, status codes, and headers. Learn how browsers and servers exchange data to deliver web content.
1. What is HTTP?
HTTP (HyperText Transfer Protocol) is the foundation of data communication on the web. It's a request-response protocol between clients and servers.
The Request-Response Cycle
1. Client (Browser) sends HTTP REQUEST
↓
2. Server processes the request
↓
3. Server sends HTTP RESPONSE
↓
4. Client receives and displays content
Example:
You type: www.example.com
↓
Browser sends: GET / HTTP/1.1
Host: www.example.com
↓
Server responds: HTTP/1.1 200 OK
Content-Type: text/html
<html>...</html>
↓
Browser renders the page
2. HTTP Methods (Verbs)
HTTP methods indicate the desired action to be performed on a resource.
Common HTTP Methods
| Method | Purpose | Safe | Idempotent |
|---|---|---|---|
| GET | Retrieve data | ✅ | ✅ |
| POST | Submit/create data | ❌ | ❌ |
| PUT | Update/replace data | ❌ | ✅ |
| PATCH | Partial update | ❌ | ❌ |
| DELETE | Remove data | ❌ | ✅ |
| HEAD | Get headers only | ✅ | ✅ |
| OPTIONS | Get allowed methods | ✅ | ✅ |
Safe: Doesn't modify server data Idempotent: Same result if repeated multiple times
GET Method
Purpose: Retrieve data from server
Characteristics:
- Data sent in URL (query parameters)
- Visible in browser history
- Can be bookmarked
- Should only retrieve data, not modify it
Example:
GET /search?q=web+development&limit=10 HTTP/1.1
Host: api.example.com
Query parameters: q=web+development and limit=10
POST Method
Purpose: Send data to server (create new resources)
Characteristics:
- Data sent in request body (not URL)
- Not visible in browser history
- Cannot be bookmarked
- Can send large amounts of data
Example:
POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
{
"name": "Alice",
"email": "alice@example.com"
}
PUT Method
Purpose: Update/replace existing resource
Example:
PUT /api/users/123 HTTP/1.1
Host: api.example.com
Content-Type: application/json
{
"name": "Alice Smith",
"email": "alice.smith@example.com"
}
DELETE Method
Purpose: Remove a resource
Example:
DELETE /api/users/123 HTTP/1.1
Host: api.example.com
3. HTTP Status Codes
Status codes tell you the result of an HTTP request.
Status Code Categories
- 1xx: Informational (request received, continuing)
- 2xx: Success (request successfully received and processed)
- 3xx: Redirection (further action needed)
- 4xx: Client Error (request has an error)
- 5xx: Server Error (server failed to fulfill valid request)
Common Status Codes
2xx Success
- 200 OK: Request succeeded
- 201 Created: New resource created
- 204 No Content: Success, but no content to return
3xx Redirection
- 301 Moved Permanently: Resource permanently moved to new URL
- 302 Found: Temporary redirect
- 304 Not Modified: Use cached version
4xx Client Errors
- 400 Bad Request: Invalid request syntax
- 401 Unauthorized: Authentication required
- 403 Forbidden: Server refuses request (no permission)
- 404 Not Found: Resource doesn't exist
- 405 Method Not Allowed: HTTP method not supported
- 429 Too Many Requests: Rate limit exceeded
5xx Server Errors
- 500 Internal Server Error: Generic server error
- 502 Bad Gateway: Invalid response from upstream server
- 503 Service Unavailable: Server temporarily unavailable
- 504 Gateway Timeout: Upstream server timeout
Status Code Examples
# Success
HTTP/1.1 200 OK
Content-Type: text/html
...
# Not Found
HTTP/1.1 404 Not Found
Content-Type: text/html
...
# Redirect
HTTP/1.1 301 Moved Permanently
Location: https://www.newurl.com
...
# Server Error
HTTP/1.1 500 Internal Server Error
Content-Type: text/html
...
::: tip 💡 Remember Status Codes
- 2xx = Success 😊
- 3xx = Redirect 🔄
- 4xx = Your mistake 🤦
- 5xx = Server's mistake 🔥 :::
4. HTTP Headers
Headers provide metadata about the request or response.
Request Headers
Common Request Headers:
GET /api/users HTTP/1.1
Host: api.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: application/json
Accept-Language: en-US,en;q=0.9
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Cookie: sessionId=abc123; userId=456
Key Request Headers:
| Header | Purpose | Example |
|---|---|---|
| Host | Target server | api.example.com |
| User-Agent | Client info | Mozilla/5.0 ... |
| Accept | Desired format | application/json |
| Authorization | Authentication | Bearer token123 |
| Cookie | Session data | sessionId=abc123 |
| Content-Type | Body format | application/json |
| Referer | Previous page | https://google.com |
Response Headers
Common Response Headers:
HTTP/1.1 200 OK
Date: Mon, 05 Oct 2025 12:00:00 GMT
Server: nginx/1.18.0
Content-Type: application/json
Content-Length: 1234
Cache-Control: max-age=3600
Set-Cookie: sessionId=xyz789; HttpOnly; Secure
Access-Control-Allow-Origin: *
Key Response Headers:
| Header | Purpose | Example |
|---|---|---|
| Content-Type | Response format | text/html; charset=UTF-8 |
| Content-Length | Body size (bytes) | 1234 |
| Cache-Control | Caching rules | max-age=3600 |
| Set-Cookie | Send cookie | sessionId=abc123 |
| Location | Redirect URL | https://newurl.com |
| Server | Server software | nginx/1.18.0 |
5. Cookies and Sessions
What are Cookies?
Cookies are small pieces of data stored in the browser and sent with every request to the same domain.
Cookie Structure:
Set-Cookie: name=value; Expires=Wed, 09 Jun 2026 10:18:14 GMT; Path=/; Secure; HttpOnly
Cookie Attributes:
| Attribute | Purpose |
|---|---|
| Name=Value | The actual data |
| Expires | Expiration date/time |
| Max-Age | Lifetime in seconds |
| Domain | Which domain can access |
| Path | Which paths can access |
| Secure | HTTPS only |
| HttpOnly | No JavaScript access |
| SameSite | CSRF protection |
Cookie Types
1. Session Cookies
- No expiration set
- Deleted when browser closes
- Used for temporary data
2. Persistent Cookies
- Has expiration date
- Survives browser restart
- Used for "Remember Me" features
3. Third-Party Cookies
- Set by different domain
- Used for tracking/ads
- Often blocked by browsers
Sessions
Session Flow:
1. User logs in
2. Server creates session
3. Server sends session ID via cookie
4. Browser stores cookie
5. Browser sends cookie with every request
6. Server validates session ID
7. User logs out → session destroyed
Example:
# Login request
POST /login HTTP/1.1
Content-Type: application/json
{"username": "alice", "password": "secret123"}
# Server response
HTTP/1.1 200 OK
Set-Cookie: sessionId=abc123xyz; HttpOnly; Secure
# Subsequent requests
GET /api/profile HTTP/1.1
Cookie: sessionId=abc123xyz
6. CORS (Cross-Origin Resource Sharing)
Same-Origin Policy
Browsers block requests to different origins for security.
Origin = Protocol + Domain + Port
| URL | Same Origin as https://example.com? |
|---|---|
https://example.com/page | ✅ Yes |
http://example.com | ❌ No (different protocol) |
https://api.example.com | ❌ No (different subdomain) |
https://example.com:8080 | ❌ No (different port) |
CORS Headers
Server must send:
Access-Control-Allow-Origin: https://yoursite.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Preflight Request (OPTIONS): For complex requests, browser sends OPTIONS first:
OPTIONS /api/users HTTP/1.1
Origin: https://yoursite.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
7. Making HTTP Requests with JavaScript
Using Fetch API
Basic GET Request:
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error))
Async/Await Version:
async function getUsers() {
try {
const response = await fetch('https://api.example.com/users')
const data = await response.json()
console.log(data)
} catch (error) {
console.error('Error:', error)
}
}
POST Request:
async function createUser(userData) {
try {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
body: JSON.stringify(userData)
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const data = await response.json()
console.log('User created:', data)
} catch (error) {
console.error('Error:', error)
}
}
// Usage
createUser({
name: 'Alice',
email: 'alice@example.com'
})
PUT Request:
async function updateUser(userId, updates) {
const response = await fetch(`https://api.example.com/users/${userId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updates)
})
return response.json()
}
DELETE Request:
async function deleteUser(userId) {
const response = await fetch(`https://api.example.com/users/${userId}`, {
method: 'DELETE'
})
if (response.status === 204) {
console.log('User deleted successfully')
}
}
8. REST API Basics
REST (Representational State Transfer) is an architectural style for APIs.
REST Principles
- Stateless: Each request contains all needed information
- Client-Server: Separation of concerns
- Cacheable: Responses can be cached
- Uniform Interface: Consistent naming and structure
RESTful URL Patterns
GET /api/users → Get all users
GET /api/users/123 → Get user with ID 123
POST /api/users → Create new user
PUT /api/users/123 → Update user 123
PATCH /api/users/123 → Partially update user 123
DELETE /api/users/123 → Delete user 123
GET /api/users/123/posts → Get posts by user 123
POST /api/users/123/posts → Create post for user 123
REST Response Format (JSON)
// Success response
{
"success": true,
"data": {
"id": 123,
"name": "Alice",
"email": "alice@example.com"
}
}
// Error response
{
"success": false,
"error": {
"code": 404,
"message": "User not found"
}
}
// List response
{
"success": true,
"data": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
],
"pagination": {
"page": 1,
"total": 100
}
}
9. Debugging HTTP with DevTools
Network Panel Analysis
Steps:
- Open DevTools (F12)
- Go to Network tab
- Perform action (load page, submit form, etc.)
- Click on a request to see details
What to Check:
Headers Tab:
- Request Method (GET, POST, etc.)
- Status Code (200, 404, 500, etc.)
- Request Headers (what you sent)
- Response Headers (what server sent)
Preview Tab:
- Formatted response preview
- For JSON: shows object structure
- For HTML: rendered preview
Response Tab:
- Raw response data
- Useful for debugging
Timing Tab:
- DNS Lookup time
- Connection time
- Server response time
- Content download time
Common Issues & Solutions
Issue: 404 Not Found
- Check URL spelling
- Verify endpoint exists
- Check API documentation
Issue: 401 Unauthorized
- Check authentication token
- Verify token hasn't expired
- Check Authorization header
Issue: 403 Forbidden
- Check user permissions
- Verify API key/credentials
- Contact server admin
Issue: 500 Server Error
- Server-side problem
- Check server logs
- Try again later
- Contact API support
Issue: CORS Error
- Server must allow your origin
- Check Access-Control headers
- Use proxy for development
10. Practical Exercises
Exercise 1.3.1: Analyze HTTP Requests
- Go to https://jsonplaceholder.typicode.com
- Open DevTools Network panel
- Click "Run" button on any example
- Answer:
- What HTTP method was used?
- What was the status code?
- What Content-Type was returned?
- How long did the request take?
Exercise 1.3.2: Make API Requests
Open the browser console and try:
// GET request
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(res => res.json())
.then(data => console.log(data))
// POST request
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: 'My Post',
body: 'This is my post content',
userId: 1
})
})
.then(res => res.json())
.then(data => console.log('Created:', data))
Exercise 1.3.3: Inspect Cookies
- Visit https://www.github.com (or any site)
- Open DevTools → Application → Cookies
- Find and list:
- How many cookies are stored?
- Which ones are HttpOnly?
- Which ones have expiration dates?
- Try deleting a cookie and refresh
Exercise 1.3.4: Test Status Codes
Use this test API:
// Test different status codes
async function testStatusCode(code) {
const response = await fetch(`https://httpstat.us/${code}`)
console.log(`Status ${code}: ${response.status} ${response.statusText}`)
}
testStatusCode(200) // OK
testStatusCode(404) // Not Found
testStatusCode(500) // Server Error
11. Knowledge Check
Question 1: What HTTP method should be used to retrieve data?
Show answer
GET - It's safe and idempotent, designed for retrieving data without modifying it.Question 2: What does a 404 status code mean?
Show answer
404 Not Found - The requested resource doesn't exist on the server.Question 3: Where is data sent in a POST request?
Show answer
In the request body (not in the URL like GET requests).Question 4: What header specifies the format of the request body?
Show answer
Content-Type (e.g., application/json, application/x-www-form-urlencoded)Question 5: What's the difference between cookies and sessions?
Show answer
Cookies are stored in the browser and sent with requests. Sessions are stored on the server, with only a session ID stored in a cookie.Question 6: What does CORS stand for and why does it exist?
Show answer
Cross-Origin Resource Sharing - It's a security mechanism that restricts web pages from making requests to different domains than the one serving the page.12. Key Takeaways
✅ HTTP is a request-response protocol for web communication ✅ HTTP methods (GET, POST, PUT, DELETE) indicate the action to perform ✅ Status codes tell you the result: 2xx success, 3xx redirect, 4xx client error, 5xx server error ✅ Headers provide metadata about requests and responses ✅ Cookies store data in the browser and are sent with every request ✅ Sessions use cookies to maintain user state across requests ✅ CORS controls cross-origin requests for security ✅ REST APIs follow predictable patterns for accessing resources ✅ Fetch API makes HTTP requests in JavaScript ✅ DevTools Network panel is essential for debugging HTTP
13. Further Resources
HTTP Specifications:
API Testing:
- JSONPlaceholder - Fake REST API
- HTTPBin - HTTP testing service
- ReqRes - Test REST API
Tools:
Next Steps
Excellent work! You now understand how browsers and servers communicate using HTTP.
In Lesson 1.4: Web Standards and W3C, you'll learn about web standards, browser compatibility, and accessibility.