What is HTTP 404 Not Found?

HTTP 404 Not Found indicates that the server cannot find the requested resource. This could mean the URL is incorrect, the resource has been moved or deleted, or the endpoint doesn't exist. Unlike server errors, 404 responses suggest the server is working correctly but cannot locate the specific resource.

404 errors are client errors, meaning the issue is typically with the request rather than the server itself.

Common Causes of HTTP 404 Errors

cURL Examples That Trigger 404 Errors

Example 1: Incorrect Endpoint URL

curl -X GET "https://api.github.com/user/repositorys"  # Typo: "repositorys" instead of "repos"

Response:

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

{
  "message": "Not Found",
  "documentation_url": "https://docs.github.com/rest"
}

Example 2: Non-existent Resource ID

curl -X GET "https://jsonplaceholder.typicode.com/users/999999"

Response:

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

{}

Example 3: Wrong API Version

curl -X GET "https://api.example.com/v3/users"  # API only supports v1 and v2

Correct cURL Examples

GitHub API - Correct Endpoint

curl -X GET "https://api.github.com/users/octocat" \
  -H "Accept: application/vnd.github.v3+json"

REST API with Proper Resource ID

curl -X GET "https://jsonplaceholder.typicode.com/users/1" \
  -H "Accept: application/json"

API with Correct Version

curl -X GET "https://api.example.com/v1/users" \
  -H "Accept: application/json" \
  -H "Authorization: Bearer your-token"

How to Debug HTTP 404 Errors

1. Verify the URL

Double-check the endpoint URL against the API documentation:

# Use verbose mode to see the actual request
curl -v -X GET "https://api.example.com/users"

2. Check API Documentation

Verify the correct endpoint format, required parameters, and API version:

# Test with a known working endpoint first
curl -X GET "https://api.github.com/zen"

3. Test Similar Endpoints

Try related endpoints to verify the base URL is correct:

# Test the API root
curl -X GET "https://api.example.com/"

# Test different endpoints
curl -X GET "https://api.example.com/status"

Handling HTTP 404 in Different Languages

Python with requests

import requests

def fetch_user(user_id):
    try:
        response = requests.get(f'https://api.example.com/users/{user_id}')
        
        if response.status_code == 404:
            print(f"User {user_id} not found")
            return None
        elif response.status_code == 200:
            return response.json()
        else:
            print(f"Unexpected status code: {response.status_code}")
            return None
            
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
        return None

# Example usage
user = fetch_user(123)
if user:
    print(f"Found user: {user['name']}")
else:
    print("User not found or request failed")

JavaScript with fetch

async function fetchUser(userId) {
  try {
    const response = await fetch(`https://api.example.com/users/${userId}`);
    
    if (response.status === 404) {
      console.log(`User ${userId} not found`);
      return null;
    }
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
    const user = await response.json();
    return user;
    
  } catch (error) {
    console.error('Failed to fetch user:', error);
    return null;
  }
}

// Example usage with error handling
fetchUser(123)
  .then(user => {
    if (user) {
      console.log('Found user:', user.name);
    } else {
      console.log('User not found');
    }
  })
  .catch(error => {
    console.error('Request failed:', error);
  });

PHP with cURL

 "https://api.example.com/users/" . $userId,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ["Accept: application/json"],
    ]);
    
    $response = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    
    if ($httpCode === 404) {
        echo "User $userId not found\n";
        curl_close($curl);
        return null;
    }
    
    if ($httpCode === 200) {
        $user = json_decode($response, true);
        curl_close($curl);
        return $user;
    }
    
    echo "Unexpected HTTP code: $httpCode\n";
    curl_close($curl);
    return null;
}

// Example usage
$user = fetchUser(123);
if ($user) {
    echo "Found user: " . $user['name'] . "\n";
} else {
    echo "User not found or request failed\n";
}
?>

Preventing HTTP 404 Errors

Best Practices to Avoid 404 Errors:

  • Validate URLs before making requests
  • Check API documentation for correct endpoints
  • Implement proper error handling for missing resources
  • Use API versioning correctly
  • Test with known good data first
  • Handle case sensitivity appropriately
  • Verify resource existence before operations

Common 404 Scenarios and Solutions

Scenario 1: Trailing Slash Sensitivity

Problem: API requires specific trailing slash format

# This might fail
curl -X GET "https://api.example.com/users"

# This might work
curl -X GET "https://api.example.com/users/"

Scenario 2: Case Sensitivity

Problem: Incorrect capitalization in URLs

# Incorrect case
curl -X GET "https://api.example.com/Users/123"

# Correct case
curl -X GET "https://api.example.com/users/123"

Scenario 3: API Version Mismatch

# Check what versions are available
curl -X GET "https://api.example.com/"

# Use the correct version
curl -X GET "https://api.example.com/v2/users/123"

Testing and Validation Strategies

1. Endpoint Discovery

# Test the API root to see available endpoints
curl -X GET "https://api.example.com/" | jq .

# Check API documentation endpoint
curl -X GET "https://api.example.com/docs"

2. Resource Validation

# List available resources first
curl -X GET "https://api.example.com/users" | jq '.[].id'

# Then request specific resource
curl -X GET "https://api.example.com/users/1"

3. Graceful Degradation

# Try multiple endpoints with fallbacks
curl -X GET "https://api.example.com/v2/users/123" || \
curl -X GET "https://api.example.com/v1/users/123" || \
echo "User not found in any API version"

Important: Always implement proper error handling for 404 responses in production applications. Consider providing helpful error messages and alternative actions for users.

API Design Considerations

For API developers, consider these patterns to improve 404 handling:

Pro Tip: Use our cURL to Code Converter to generate robust error-handling code in your preferred programming language that properly manages 404 responses!