What are API Methods?
HTTP Methods #
HTTP methods, also known as “verbs,” define the type of action to be performed on a resource. Here are the most commonly used HTTP methods:
1. GET #
- Purpose: Retrieve data from the server.
- Idempotent: Yes (multiple identical requests will yield the same result).
- Sample Example: Fetching a list of users.
GET /users HTTP/1.1
Host: example.com
- Response:
[
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Jane Smith"}
]
2. POST #
- Purpose: Send data to the server to create a new resource.
- Idempotent: No (sending the same request multiple times can create multiple resources).
- Sample Example: Creating a new user.
POST /users HTTP/1.1
Host: example.com
Content-Type: application/json
{
"name": "John Doe",
"email": "john.doe@example.com"
}
- Response:
HTTP/1.1 201 Created
Location: /users/1
3. PUT #
- Purpose: Update an existing resource or create a resource if it doesn’t exist.
- Idempotent: Yes (sending the same request multiple times will result in the same state).
- Sample Example: Updating a user’s information.
PUT /users/1 HTTP/1.1
Host: example.com
Content-Type: application/json
{
"name": "John Doe",
"email": "john.newemail@example.com"
}
- Response:
HTTP/1.1 200 OK
4. DELETE #
- Purpose: Remove a resource from the server.
- Idempotent: Yes (deleting a resource multiple times results in the same state, i.e., the resource being absent).
- Sample Example: Deleting a user.
DELETE /users/1 HTTP/1.1
Host: example.com
- Response:
HTTP/1.1 204 No Content
5. PATCH #
- Purpose: Apply partial updates to a resource.
- Idempotent: Yes (the same PATCH request will result in the same state).
- Sample Example: Updating only the email of a user.
PATCH /users/1 HTTP/1.1
Host: example.com
Content-Type: application/json
{
"email": "john.updated@example.com"
}
- Response:
HTTP/1.1 200 OK
6. HEAD #
- Purpose: Same as GET, but it only retrieves the headers, not the body.
- Idempotent: Yes.
- Sample Example: Checking if a resource exists without downloading it.
HEAD /users/1 HTTP/1.1
Host: example.com
- Response:
HTTP/1.1 200 OK
Content-Length: 348
Content-Type: application/json