API Design: HTTP Methods Made Simple

APIs leverage HTTP methods to comprehend your intentions. HTTP methods are case-sensitive keywords that specify the desired action to be performed on a specific resource within an API. They form an essential part of the request line in an HTTP request message.

Common HTTP Methods

GET

This method retrieves data from a specified resource.

Example: GET /products/123 → Fetches information about a product with ID 123.

POST

Use POST to create a new resource within the API.

Example: POST /users → Creates a new user account with data sent in the request body.

PUT

This method updates a complete existing resource. PUT requires providing the entire updated resource representation.

Example: PUT /orders/456 → Updates an order with ID 456 with data sent in the request body.

DELETE

As the name suggests, DELETE removes a resource from the API.

Example: DELETE /shoppingCart/items/789 → Deletes a specific item (ID: 789) from your shopping cart.

PATCH

Unlike PUT, which replaces the entire resource, PATCH allows for partial updates.

Example: PATCH /tasks/101 → Updates the status of a task (ID: 101) to “completed” in the request body.

Less Common HTTP Methods

HEAD: Retrieves only the header information (metadata) about a resource, similar to asking the waiter if they have a specific dish in stock without placing an order.

OPTIONS: Used to discover the supported HTTP methods for a specific resource, akin to inquiring about available menu options before placing an order.

TRACE: Primarily for debugging purposes, it echoes the entire request back to the client.

Basic Guidelines

  • Align methods with their intended actions (use GET for retrieving, POST for creating, etc.).
  • Certain methods (like GET, PUT, DELETE) should be idempotent, meaning repeating the request with the same data produces the same outcome.
  • APIs should return appropriate HTTP error codes (e.g., 404 Not Found, 400 Bad Request) to indicate issues with requests.

REST

REST (REpresentational State Transfer) is a popular architectural style for APIs. It heavily emphasizes the use of HTTP methods for a well-defined interaction style:

  • GET: Retrieves resources.
  • POST: Creates new resources.
  • PUT: Updates existing resources.
  • DELETE: Deletes resources.