Home > front end >  Best API response format in Json
Best API response format in Json

Time:12-08

Which one is the best for API response ?

  1. In here I return some meta information with actual data. Although I am not sure they need to use those meta information or not.
{
    "version": "1.0.0",
    "isError": false,
    "statusCode": 200,
    "message": "Permission Object",
    "data": {
        "id": 1,
        "name": "user create",
        "created_at": "2022-11-30T10:18:20.000000Z"
    }
}
  1. In second example I am returning only the relevant data.
{
    "id": 1,
    "name": "user create",
    "created_at": "2022-11-30T10:18:20.000000Z"
}

Give me suggestion if there are other better way. Thanks in advance.

CodePudding user response:

I noticed you've used the tag REST, so I assume you are thinking about a RESTful API implementation and have some knowledge about RESTful API design.

If you need some best practices, a couple of them I think are useful. here and here.

Looking at your examples, I would prefer the second option, the reasons are:

  1. IsError can be determined by the HTTP response, e.g. 400, 500, 200, 201, so it's redundant.
  2. Status and Message are also redundant when the response is successful but could be useful in an error state, like in ASP.NET, you can use the ProblemDetails response (you can customize the way you want).
{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "Unable to create a new user due to missing name",
    "status": 400,
    "traceId": "00-0aa7d64ad154a1e1853c413a0def982d-195d3558c90f7876-00"
}
  1. version is an interesting one. Usually, it can be included in the request header or URL. If the API cannot handle the version requested, then it should return an error in the problem details.

Thus, I prefer the second option and send a problem details response when there is an error.

CodePudding user response:

JSON API is a format that works with HTTP. It delineates how clients should request or edit data from a server, and how the server should respond to said requests.

  • Related