DEV Community

CodeWithVed
CodeWithVed

Posted on • Edited on

How to write a Good APIs

Explains Postel's Law, also known as the Robustness Principle, and its practical application in API design. The law is summarized by the phrase: "Be conservative in what you send and be liberal in what you accept."

Conservative in Sending Data: When an API sends data, it should be strict and ensure the data's integrity and completeness. For example, when providing user profile details to a frontend application, the API must verify that all required fields are present and that the data is in the correct format, such as ensuring a profile image URL is a valid URL. This approach ensures that the client application can reliably predict and handle the data it receives.

Liberal in Accepting Data: Conversely, when an API receives data, it should be flexible and accommodating. The API should be designed to handle minor variations or imperfections in the incoming data. For instance:

  • If a user submits a biography that exceeds the character limit, the API should accept the input, trim it to the acceptable length, and then save it, rather than rejecting the request outright.
  • Similarly, if a username is submitted with varied casing, the API should accept it and convert it to a consistent format (e.g., lowercase) before storing it in the database.

By implementing Postel's Law, developers can create APIs that are both robust and user-friendly, leading to a more resilient and seamless experience for the end-user.

Top comments (0)