8

My take on the shape of a REST API response

 1 year ago
source link: https://pawelgrzybek.com/my-take-on-the-shape-of-a-rest-api-response/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

My take on the shape of a REST API response

Published: 2023.07.18 · 2 minutes read

I have built a few REST APIs and seen many approaches to the response interface. A few specifications try to standardize the response shape, such as JSON:API, OData JSON Format, and JSend. I prefer to keep things simple, so I have developed an interface that works well for me in most cases and wanted to share it with you.

Successful/error response#

Look at the example of a successful response and the one in case of an error. This interface served me well on multiple projects.

{
  "status": "success",
  "statusCode": 200,
  "data": {
    "user": {
      "id": 123,
      "name": "Paweł Grzybek"
    }
  },
  "error": null
}
{
  "status": "error",
  "statusCode": 404,
  "data": null,
  "error": "Uuups! Not found."
}

You may wonder why I keep status and statusCode if this information can be inferred from the raw response. The convenience of having all this information in the response body makes my job a lot easier. Laziness is the short answer. Objects in the data field are explicitly grouped by the entity name, making it almost impossible to confuse when working with more complex payloads. A single string as an error message is enough for most cases.

That’s all for today. I hope you find this approach useful — it’s not a silver bullet, but it works great for me and can be a good starting point for your next project.

Did you like it? Please share it with your friends or get me a beer coffee. Thanks!

Leave a comment#

Name:
Website (optional):
GitHub (optional):
Comment:

👆 you can use Markdown here

Save my data for the next time I comment

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK