Definition
An HTTP request is a message sent from a client (browser, mobile app, API consumer) to a server to request a specific resource or trigger an action. Every web interaction begins with an HTTP request.
The request consists of three main parts:
- Request Line - Method, URI, and HTTP version
- Headers - Metadata about the request (authentication, content type, etc.)
- Body (optional) - Data payload for methods like POST, PUT, PATCH
HTTP requests follow a strict format defined in RFC 7231 and are the foundation of RESTful APIs and web communication.
Example
A typical HTTP GET request to retrieve user data:
GET /api/users/123 HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accept: application/json
User-Agent: Mozilla/5.0
A POST request to create a new resource:
POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Length: 89
{
"name": "Alice Smith",
"email": "[email protected]",
"role": "developer"
}
Code Example
JavaScript (Fetch API):
// GET Request
const getUser = async (userId) => {
const response = await fetch(`https://api.example.com/users/${userId}`, {
method: 'GET',
headers: {
'Authorization': 'Bearer YOUR_TOKEN',
'Accept': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
};
// POST Request
const createUser = async (userData) => {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN'
},
body: JSON.stringify(userData)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
};
// Usage
const newUser = {
name: 'Alice Smith',
email: '[email protected]',
role: 'developer'
};
createUser(newUser)
.then(user => console.log('Created:', user))
.catch(error => console.error('Error:', error));
Python (requests library):
import requests
# GET Request
def get_user(user_id):
response = requests.get(
f'https://api.example.com/users/{user_id}',
headers={
'Authorization': 'Bearer YOUR_TOKEN',
'Accept': 'application/json'
}
)
response.raise_for_status()
return response.json()
# POST Request
def create_user(user_data):
response = requests.post(
'https://api.example.com/users',
json=user_data,
headers={
'Authorization': 'Bearer YOUR_TOKEN'
}
)
response.raise_for_status()
return response.json()
# Usage
new_user = {
'name': 'Alice Smith',
'email': '[email protected]',
'role': 'developer'
}
try:
user = create_user(new_user)
print(f'Created: {user}')
except requests.exceptions.HTTPError as e:
print(f'Error: {e}')
Diagram
sequenceDiagram
participant Client
participant Server
Note over Client: Prepare Request
Client->>Client: Set Method (GET/POST/etc)
Client->>Client: Add Headers
Client->>Client: Add Body (if needed)
Note over Client,Server: Send Request
Client->>Server: HTTP Request
Note right of Server: Request Line
Headers
Body (optional)
Note over Server: Process Request
Server->>Server: Validate
Server->>Server: Authenticate
Server->>Server: Execute Logic
Note over Client,Server: Send Response
Server->>Client: HTTP Response
Note left of Client: Status Code
Headers
Body
Note over Client: Handle Response
Client->>Client: Parse Response
Client->>Client: Update UI/State
Analogy
Think of an HTTP request like ordering at a restaurant:
- Request Line β “I’d like the Caesar salad” (what you want)
- Headers β “No croutons, dressing on the side” (preferences/metadata)
- Body β Custom instructions written on a note (additional data)
The waiter (server) takes your order (request), processes it in the kitchen, and brings back your meal (response).
Best Practices
- Use Correct HTTP Method - GET for reads, POST for creates, PUT/PATCH for updates, DELETE for removals
- Include Required Headers -
Host,Content-Type,Authorizationwhen needed - Set Timeouts - Always configure request timeouts to prevent hanging connections
- Handle Errors Gracefully - Check status codes and handle network failures
- Use HTTPS - Always encrypt sensitive data in transit
- Validate Input - Sanitize data before sending in request body
- Set User-Agent - Identify your client for server logs and analytics
Common Mistakes
- Missing Content-Type - Sending JSON without
Content-Type: application/jsonheader - Wrong HTTP Method - Using GET with a body, or POST when GET is appropriate
- No Error Handling - Not checking response status codes or network errors
- Hardcoded URLs - Not using environment variables for API endpoints
- Sending Secrets in URLs - Never put API keys or tokens in query parameters
- Forgetting CORS Headers - Not setting proper headers for cross-origin requests
- No Retry Logic - Not implementing exponential backoff for transient failures