What is a right way for REST API response?

10,644

There is many ways to design you API response. It is conditional to your architecture, technology, and other aspects.

Based on your example, I would respond this way

Successful request:

{
    "status": "success",
    "data": {
            /* Application-specific data would go here. */
    },
    "message": null /* Or optional success message */
}

Failed request:

{
    "status": "error",
    "code": 404,
    "data": null, /* or optional error payload */
    "message": "Error xyz has occurred"
}

For more info about this topic take a look at this links

Standard JSON API response format?

Best Practices for Designing a Pragmatic RESTful API

REST API Error Codes 101

Share:
10,644

Related videos on Youtube

A. Innokentiev
Author by

A. Innokentiev

Updated on June 04, 2022

Comments

  • A. Innokentiev
    A. Innokentiev almost 2 years

    What is a best practice for REST API response structure and layout?

    Example of scrath:

    Success response:

    {
        "status": "success",
        "data": # some data here
    }
    

    Fail response:

    {
        "status": "fail",
        "data": {
            "code": # some error code,
            "message": # some error explaining message
        }
    }
    
  • xIcarus
    xIcarus over 3 years
    I've never understood this, maybe someone could give me a reason: why return "status" at all? The client can figure out whether the call was successful based on the response status code. It's pretty self explanatory that if the status code is 200 everything went fine, or that 401 requires authentication (you can even specify a custom tailored message in case of an error). Why would I repeat the response status code in the body?
  • aderchox
    aderchox about 2 years
    @xIcarus Read the three reasons given here by an experienced developer: shazow.net/posts/how-i-design-json-api-responses