Understanding HTTP Methods and Status Codes

A comprehensive guide to HTTP methods and their status codes

Featured image



Overview

HTTP methods define how clients communicate with web servers. Let’s explore each method and their corresponding status codes.

HTTP Request/Response Structure

HTTP Request Format
  [METHOD] [URL] HTTP/[VERSION]
  [Headers]

  [Request Body]
  
Example
  POST /api/users HTTP/1.1
  Host: example.com
  Content-Type: application/json
  Authorization: Bearer token123

  {
    "name": "John Doe",
    "email": "john@example.com"
  }
  
HTTP Response Format
  HTTP/[VERSION] [STATUS_CODE] [STATUS_TEXT]
  [Headers]

  [Response Body]
  
Example
  HTTP/1.1 201 Created
  Content-Type: application/json
  Location: /api/users/123

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


graph TD; A[HTTP Request Methods] --> B[🔍 GET Request]; A --> C[POST Request]; A --> D[HEAD Request]; B --> B1[Used when typing URL in browser]; B1 --> B2[GET /cat.png]; B2 --> B3[200 OK \n Content-Type: image/png]; B3 --> B4[Display Cat Image]; C --> C1[Submitting a form]; C1 --> C2[POST /sign_up \n Content-Type: application/json]; C2 --> C3[200 OK \n Content-Type: text/html]; C3 --> C4[Display Sign-up Page]; D --> D1[Similar to GET but no response body]; D1 --> D2[HEAD /cat.png]; D2 --> D3[200 OK \n Content-Type: image/png]; D3 --> D4[No image, only headers]; %% Explanation B -.-> E[GET: Usually no request body]; C -.-> F[POST: Usually sends data in request body]; E -.-> G[GET doesn't change server state]; F -.-> H[POST can change server state];



🔍 HTTP Methods


GET

  • Used for retrieving information
  • Read-only operations
  • Doesn't modify server data

POST

  • Creates new resources
  • Sends data to server
  • More secure than GET for data transmission

HEAD

  • Similar to GET but returns headers only
  • No response body
  • Efficient for metadata checks

PUT

  • Updates entire resource
  • Creates if doesn't exist
  • Requires complete resource data

DELETE

  • Removes specified resource
  • Usually returns empty response
  • Should be used carefully

PATCH

  • Partial resource modification
  • More efficient than PUT
  • Updates specific fields

OPTIONS

  • Lists available methods
  • Returns "Allow" header
  • Used for API discovery

TRACE

  • Diagnostic purposes
  • Returns exact request
  • Debugging tool

CONNECT

  • Creates network tunnel
  • Used for SSL/TLS
  • Proxy connections


HTTP Methods in Detail

GET

Purpose: Retrieve data from a specified resource


Idempotent: Yes


Safe: Yes (doesn't modify resources)


Request Body: Not typically used


Cacheable: Yes



Example Request:
  GET /api/users/123 HTTP/1.1
  Host: example.com
  Accept: application/json
  
Example Response:
  HTTP/1.1 200 OK
  Content-Type: application/json

  {
    "id": "123",
    "name": "John Doe",
    "email": "john@example.com"
  }
  
Common Use Cases:
  • Loading web pages
  • Retrieving API data
  • Downloading files
  • Searching (via query parameters)

POST

Purpose: Create a new resource


Idempotent: No (multiple identical requests may create multiple resources)


Safe: No


Request Body: Yes


Cacheable: Only if explicitly specified



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

  {
    "name": "Jane Smith",
    "email": "jane@example.com"
  }
  
Example Response:
  HTTP/1.1 201 Created
  Content-Type: application/json
  Location: /api/users/456

  {
    "id": "456",
    "name": "Jane Smith",
    "email": "jane@example.com"
  }
  
Common Use Cases:
  • Form submissions
  • File uploads
  • Creating new records in a database
  • Authentication/login



PUT

Purpose: Update an existing resource or create if it doesn't exist


Idempotent: Yes (multiple identical requests have the same effect)


Safe: No


Request Body: Yes (contains complete resource)


Cacheable: No



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

  {
    "name": "John Doe Updated",
    "email": "john@example.com"
  }
  
Example Response:
  HTTP/1.1 200 OK
  Content-Type: application/json

  {
    "id": "123",
    "name": "John Doe Updated",
    "email": "john@example.com"
  }
  
Common Use Cases:
  • Updating existing resources with complete data
  • Replacing an entire document
  • Creating resources with client-specified IDs



DELETE

Purpose: Remove a resource


Idempotent: Yes (deleting an already deleted resource has no effect)


Safe: No


Request Body: Optional


Cacheable: No



Example Request:
  DELETE /api/users/123 HTTP/1.1
  Host: example.com
  
Example Response:
  HTTP/1.1 204 No Content
  
Common Use Cases:
  • Removing database records
  • Canceling subscriptions
  • Deleting files
  • Removing user accounts

PATCH

Purpose: Apply partial modifications to a resource


Idempotent: No (depends on implementation)


Safe: No


Request Body: Yes (contains partial resource)


Cacheable: No



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

  [
    { "op": "replace", "path": "/name", "value": "John Updated" }
  ]
  
Alternative JSON Format:
  PATCH /api/users/123 HTTP/1.1
  Host: example.com
  Content-Type: application/json

  {
    "name": "John Updated"
  }
  
Example Response:
  HTTP/1.1 200 OK
  Content-Type: application/json

  {
    "id": "123",
    "name": "John Updated",
    "email": "john@example.com"
  }
  
Common Use Cases:
  • Updating specific fields of a resource
  • User profile updates
  • Status changes
  • Any partial update operation



HEAD

Purpose: Retrieve headers only without body


Idempotent: Yes


Safe: Yes


Request Body: No


Cacheable: Yes



Example Request:
  HEAD /api/files/large-image.jpg HTTP/1.1
  Host: example.com
  
Example Response:
  HTTP/1.1 200 OK
  Content-Type: image/jpeg
  Content-Length: 2578921
  Last-Modified: Wed, 15 Jan 2025 14:12:33 GMT
  
Common Use Cases:
  • Checking if a resource exists
  • Checking file size before downloading
  • Checking if resource is modified (with If-Modified-Since)
  • Testing URL validity



OPTIONS

Purpose: Get information about communication options


Idempotent: Yes


Safe: Yes


Request Body: No


Cacheable: No



Example Request:
  OPTIONS /api/users HTTP/1.1
  Host: example.com
  
Example Response:
  HTTP/1.1 200 OK
  Allow: GET, POST, PUT, DELETE, HEAD, OPTIONS
  Access-Control-Allow-Methods: GET, POST, PUT, DELETE
  Access-Control-Allow-Headers: Content-Type, Authorization
  
Common Use Cases:
  • CORS preflight requests
  • API discovery
  • Server capability detection



📊 HTTP Status Codes


ℹ️

1xx (Informational)

Request received

Processing continues

2xx (Success)

Request succeeded

Data received and accepted

🔀

3xx (Redirection)

Additional action needed

Resource moved

🚫

4xx (Client Error)

Invalid request

Resource not found

⚠️

5xx (Server Error)

Server failed

Internal issues


Common HTTP Status Codes in Detail

1xx - Informational Responses

Code Status Description
100 Continue Server has received request headers and client should proceed with request body
101 Switching Protocols Server is switching to a different protocol as requested by client
102 Processing Server has received and is processing the request, but no response is available yet
103 Early Hints Server is sending some response headers before final HTTP message



2xx - Success Responses

Code Status Description Typical Use
200 OK Request succeeded Standard response for successful GET requests
201 Created Request succeeded and a new resource was created Successful response for POST or PUT requests that create resources
202 Accepted Request has been accepted for processing but not completed Asynchronous operations
204 No Content Request succeeded but no content to return Common for DELETE operations or updates that don't return content
206 Partial Content Server is delivering only part of the resource Range requests for large files or resumable downloads



3xx - Redirection Responses

Code Status Description Typical Use
301 Moved Permanently Resource has permanently moved to a new URL URL changes, domain migrations
302 Found Resource temporarily located at a different URL Temporary redirects
304 Not Modified Resource hasn't been modified since last request Caching operations with conditional requests
307 Temporary Redirect Resource temporarily located at another URL (preserves method) Similar to 302 but stricter about preserving the HTTP method
308 Permanent Redirect Resource permanently moved (preserves method) Similar to 301 but stricter about preserving the HTTP method



4xx - Client Error Responses

Code Status Description Typical Use
400 Bad Request Server cannot process request due to client error Malformed request syntax, invalid parameters
401 Unauthorized Authentication required for resource access Missing or invalid authentication credentials
403 Forbidden Server understood request but refuses to authorize Insufficient permissions despite authentication
404 Not Found Resource does not exist Invalid URLs, non-existent resources
405 Method Not Allowed HTTP method not supported for requested resource Using POST on a read-only endpoint, etc.
409 Conflict Request conflicts with current state of the resource Concurrent updates, version conflicts
413 Payload Too Large Request entity larger than server willing to process File upload size limits
429 Too Many Requests User has sent too many requests in a given time Rate limiting



5xx - Server Error Responses

Code Status Description Typical Use
500 Internal Server Error Generic server error message Unexpected conditions, exceptions, server bugs
501 Not Implemented Server does not support functionality required Unsupported HTTP methods or features
502 Bad Gateway Server acting as gateway received invalid response Problems with upstream servers, proxies
503 Service Unavailable Server temporarily unable to handle request Server overloaded, maintenance, temporary outages
504 Gateway Timeout Gateway or proxy did not receive response in time Slow upstream servers


REST API Best Practices

REST API Design Principles



  • Use HTTP Methods Correctly
    • GET for reading resources
    • POST for creating resources
    • PUT for updating entire resources
    • PATCH for partial updates
    • DELETE for removing resources
  • Proper HTTP Status Codes
    • Use appropriate status codes for different scenarios
    • Be specific with error status codes
  • Resource-Oriented URLs
    • Use nouns, not verbs (e.g., /users, not /getUsers)
    • Use plural nouns for collections (/users)
    • Use singular nouns with identifiers for individual resources (/users/123)
  • Versioning
    • Include version in URL (/v1/users) or headers
    • Never release breaking changes without version change
  • Filtering, Sorting, Pagination
    • Use query parameters for filtering (?status=active)
    • Support sorting (?sort=name:asc)
    • Implement pagination (?page=2&limit=10)
  • Consistent Error Handling
    • Return descriptive error messages
    • Include error codes and documentation links when possible
  • HATEOAS (Hypermedia as the Engine of Application State)
    • Include links to related resources in responses
    • Help clients navigate API without hardcoded URLs



Reference