Skip to content
Theme:

My take on the shape of a REST API response

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.

Comments

  • N
    Nicolas Danelon

    I love this post so much, if you have analytics and someone reads this from Italy or Argentina I can guarantee that is me or someone new in my team. Thanks!

    👆 you can use Markdown here

    Your comment is awaiting moderation. Thanks!
    • Paweł Grzybek
      Paweł Grzybek

      Ooh, I'm glad it helped you out! Unfortunately, I don't have any analytics script on this page. But I appreciate you passing it over to your team members, Nicolas.

      👆 you can use Markdown here

      Your comment is awaiting moderation. Thanks!
  • s
    saif

    may be this can be updated now.

    when success with status code with the request only

    {
       "data" : {},
       "meta_data" : {},
       "error" : null
    }
    

    when error with status code of error in the request

    {
       "data" : null,
       "meta_data" : {},
       "error" : {}
    }
    

    👆 you can use Markdown here

    Your comment is awaiting moderation. Thanks!
    • Paweł Grzybek
      Paweł Grzybek

      Personal preference. All are valid. The article describes how I do it, and I do it like in almost unchanged way ever since I published this post. Your suggestion is also valid and nice one.

      👆 you can use Markdown here

      Your comment is awaiting moderation. Thanks!
      • s
        saif

        Thanks

        👆 you can use Markdown here

        Your comment is awaiting moderation. Thanks!

Leave a comment

👆 you can use Markdown here

Your comment is awaiting moderation. Thanks!