HTTP (HyperText Transfer Protocol) methods define the actions that can be performed on resources via a web server. As developers, it’s crucial to understand how each method works to build efficient, secure, and scalable APIs. Let’s dive into the most commonly used HTTP methods and their characteristics.
1. GET
-
Purpose: Retrieves data from the server.
-
Idempotent: Yes (multiple requests will not cause changes).
-
Safe: Yes (no modifications are made on the server).
Request Example:
GET /api/user/1 HTTP/1.1 Host: test.com
Response Example:
{
"name": "Test User",
"email": "user@test.com"
}
2. POST
-
Purpose: Submits data to the server to be processed.
-
Idempotent: No (repeating the request may cause different outcomes).
-
Safe: No (the server processes and stores new data).
Request Example:
POST /api/user HTTP/1.1 Host: test.com Content-Type: application/json { "name": "Test User", "email": "user@test.com" }
Response Example:
HTTP/1.1 201 Created Location: /api/user/1
3. PUT
-
Purpose: Updates or replaces a resource at a specified URL.
-
Idempotent: Yes.
-
Safe: No.
Request Example:
PUT /api/user/1 HTTP/1.1 Host: test.com Content-Type: application/json { "name": "New Name", "email": "user@test.com" }
Response Example:
{
"name": "New Name",
"email": "user@test.com"
}
4. DELETE
-
Purpose: Deletes a resource at the specified URL.
-
Idempotent: Yes.
-
Safe: No.
Request Example:
DELETE /api/user/1 HTTP/1.1 Host: test.com
Response Example:
HTTP/1.1 204 No Content
5. PATCH
-
Purpose: Applies partial modifications to a resource.
-
Idempotent: Yes.
-
Safe: No.
Request Example:
PATCH /api/user/1 HTTP/1.1 Host: test.com Content-Type: application/json { "email": "new.user@test.com" }
Response Example:
{
"name": "Test User",
"email": "new.user@test.com"
}
6. HEAD
-
Purpose: Retrieves headers and metadata for a resource without the actual content.
-
Idempotent: Yes.
-
Safe: Yes.
Request Example:
HEAD /api/user/profile/123 HTTP/1.1 Host: test.com
Response Example:
HTTP/1.1 200 OK Content-Type: application/json Content-Length: 198 Last-Modified: Wed, 28 Sep 2023 12:00:00 GMT ETag: "abcdef123456" Cache-Control: public, max-age=3600
7. OPTIONS
-
Purpose: Retrieves information about the communication options available for a resource.
-
Idempotent: Yes.
-
Safe: Yes.
Request Example:
OPTIONS /api/user/1 HTTP/1.1 Host: test.com
Response Example:
HTTP/1.1 200 OK Allow: GET, HEAD, OPTIONS
These HTTP methods form the foundation for interacting with RESTful APIs. Understanding how and when to use each of these methods is key to effective API design.
