DEV Community

Lokesh Choudhary Programmer
Lokesh Choudhary Programmer

Posted on • Edited on

Understanding HTTP Verbs and Better Error Handling in APIs

Image description

When designing APIs, it's crucial to understand how HTTP verbs work to manage resources and handle errors effectively. In this article, we’ll explore the most commonly used HTTP verbs and discuss better error handling techniques for a smoother development experience.

HTTP Verbs

1. GET - Read

  • Purpose: The GET verb is used to retrieve data from the server. It’s a read-only operation and does not modify any resources.
  • Example Use Case: Fetching user details or product information.
  GET /users/123
Enter fullscreen mode Exit fullscreen mode

2. POST - Create

  • Purpose: The POST verb is used to create a new resource on the server. It doesn't matter if the resource already exists. If it does, a new instance might be created.
  • Example Use Case: Creating a new user, submitting a form, or uploading a file.
  POST /users
Enter fullscreen mode Exit fullscreen mode

3. PUT - Update (or Create)

  • Purpose: The PUT verb is used to update an existing resource. If the resource does not exist, a new one is created. It’s used when you want to replace the entire resource.
  • Example Use Case: Updating user details where you want to replace all attributes of the user.
  PUT /users/123
Enter fullscreen mode Exit fullscreen mode

4. PATCH - Update (Partial)

  • Purpose: The PATCH verb is used to make partial updates to an existing resource. Unlike PUT, it doesn’t require sending the entire resource data—just the fields that need updating.
  • Example Use Case: Updating only the user’s email address.
  PATCH /users/123
Enter fullscreen mode Exit fullscreen mode

5. DELETE - Delete

  • Purpose: The DELETE verb is used to remove a resource from the server.
  • Example Use Case: Deleting a user or removing an item from a shopping cart.
  DELETE /users/123
Enter fullscreen mode Exit fullscreen mode

Better Error Handling: error vs res.ok

In API development, robust error handling is crucial for debugging and providing a better user experience. Let’s discuss some techniques for managing errors effectively.

1. Error Object

  • When something goes wrong in your API (such as invalid data or server issues), you can throw an error object that provides details about the issue.
    • Example: Throwing an error if the user is not found.
  if (!user) {
    throw new Error('User not found');
  }
Enter fullscreen mode Exit fullscreen mode

2. res.ok vs Custom Error Messages

  • res.ok: In many frameworks, the res.ok property is a simple way to check if the response status is in the range of 2xx (indicating success). It returns true if the request was successful.

Example:

  if (res.ok) {
    console.log('Request successful');
  } else {
    console.log('Request failed');
  }
Enter fullscreen mode Exit fullscreen mode
  • Custom Error Handling: Sometimes, res.ok isn’t enough. You need more specific error handling to differentiate between various failure scenarios (e.g., client errors, server errors). You can use the response’s status code and provide custom error messages.

Example:

  if (!res.ok) {
    const errorDetails = await res.json();
    throw new Error(`Error ${res.status}: ${errorDetails.message}`);
  }
Enter fullscreen mode Exit fullscreen mode

3. Custom Error Handling Example:

If a user tries to create a duplicate resource, handle it like this:

async function createUser(data) {
  const res = await fetch('/users', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: { 'Content-Type': 'application/json' },
  });

  if (!res.ok) {
    const errorDetails = await res.json();
    if (res.status === 409) {
      throw new Error('User already exists');
    }
    throw new Error(errorDetails.message);
  }

  return res.json();
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Using the right HTTP verbs in the right context makes your API design clear and efficient. Always remember that good error handling is not just about checking res.ok, but providing meaningful error messages and handling edge cases. These small improvements lead to better user experience and smoother development cycles.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more