Activity 29: HTTP Methods

In RESTful APIs, HTTP methods define the actions that can be performed on resources. The primary methods are GET, POST, PUT, DELETE, and PATCH. Here's an overview of each:

1. GET: Retrieve Data

The GET method is used to retrieve data from a server. It is a safe and idempotent operation, meaning it does not modify the resource and can be called multiple times without different outcomes.

Use Cases:

  • Fetching a list of users.

  • Retrieving details of a specific product.

Example: To retrieve information about a user with ID 123:

GET /users/123

2. POST: Create a New Resource

The POST method sends data to the server to create a new resource. Unlike GET, POST is not idempotent; multiple identical requests can result in multiple resources being created.

Use Cases:

  • Creating a new user account.

  • Submitting a form to add a new blog post.

Example: To create a new user:

POST /users
Body:
{
  "name": "John Doe",
  "email": "john.doe@example.com"
}

3. PUT: Update an Existing Resource

The PUT method updates an existing resource with new data. It is idempotent, meaning multiple identical requests will have the same effect as a single request. PUT typically requires the client to send the complete resource representation.

Use Cases:

  • Updating a user's profile information.

  • Modifying the details of a product.

Example: To update user 123's information:

PUT /users/123
Body:
{
  "name": "John Doe",
  "email": "john.doe@example.com",
  "address": "123 Main St"
}

4. DELETE: Remove a Resource

The DELETE method removes a resource from the server. It is idempotent; calling it multiple times will have the same effect as calling it once.

Use Cases:

  • Deleting a user account.

  • Removing a product from the catalog.

Example: To delete user 123:

DELETE /users/123

5. PATCH: Apply Partial Updates

The PATCH method applies partial modifications to a resource. Unlike PUT, which replaces the entire resource, PATCH only updates the specified fields. It is not necessarily idempotent.

Use Cases:

  • Updating a user's email address.

  • Changing the status of an order.

Example: To update user 123's email:

PATCH /users/123
Body:
{
  "email": "new.email@example.com"
}

Key Differences Between PUT and PATCH:

  • PUT replaces the entire resource with the new data provided. If a field is omitted in the PUT request, it may be set to null or removed, depending on the server's implementation.

  • PATCH applies partial updates, modifying only the specified fields without affecting the rest of the resource.

Understanding these HTTP methods is crucial for designing RESTful APIs that are intuitive and efficient.

0
Subscribe to my newsletter

Read articles from John Carlo Regala directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

John Carlo Regala
John Carlo Regala