DEV Community

Cover image for API Design
Kyle Parisi
Kyle Parisi

Posted on • Edited on

API Design

Reference

First and foremost I'd like to reference everything in this article. Please read that for all the details. There are 3 things I would highlight if we were working together.

Entities

Almost all routes should represent an entity or a collection of entities. This means pagination and appropriate filter abilities for the client to use. If the client requests an entity be updated, the entity should be in the response. The reference above covers this topic well.

Bulk Operations

Bulk operations are not covered in the article above. My preference is the following:

POST /route
...headers

[{ids: [1, 3], status: 0}, {ids: [2], status: 1}]
Enter fullscreen mode Exit fullscreen mode

This should return the modified entities so that the client can merge the data into it's state.

Errors

The last topic, which I'd like to highlight is errors. Use 4xx http status for client issues and 5xx for server side issues. Most js client libraries automatically resolve 4xx and 5xx http status codes as errors. So in my opinion using the literally correct http status code is not a hard requirement. The response signature should be:

{
  "message" : "Something bad happened :(",
  "description" : "More details about the error here"
}
Enter fullscreen mode Exit fullscreen mode
{
  "message" : "Validation Failed",
  "errors" : [
    {
      "field" : "first_name",
      "message" : "First name cannot have fancy characters"
    },
    {
       "field" : "password",
       "message" : "Password cannot be blank"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Most of the time the client should be able to put the message field directly into the interface. This means it should be human readable and understandable to the end user. The message should also be < 200 characters.

Extra

  • JSON keys should never have a space
  • If a request sends Accept: application/json header, the backend should respectfully respond in kind.

Great! Now we can work together!

Top comments (2)

Collapse
 
fillippeyton profile image
Fillip Peyton

Entities has got to be my #1 priority when interfacing with an API as well. Good call!

I don't agree with this one though.

Most of the time the client should be able to put the message field directly into the interface.

While the message should be a human readable message, its not readable if it is in a language the user does not understand. Either some sort of translation key should be sent or the client should translate a 401 into the appropriate translation.

Collapse
 
kyleparisi profile image
Kyle Parisi

Good point.