Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a right way for REST API response?

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
    }
}
like image 962
A. Innokentiev Avatar asked May 16 '16 13:05

A. Innokentiev


People also ask

How do you handle a REST API response?

The simplest way we handle errors is to respond with an appropriate status code. Here are some common response codes: 400 Bad Request – client sent an invalid request, such as lacking required request body or parameter. 401 Unauthorized – client failed to authenticate with the server.

What should a REST API return?

The API should always return sensible HTTP status codes. API errors typically break down into 2 types: 400 series status codes for client issues & 500 series status codes for server issues. At a minimum, the API should standardize that all 400 series errors come with consumable JSON error representation.

What is a good API response?

Generally, APIs that are considered high-performing have an average response time between 0.1 and one second. At this speed, end users will likely not experience any interruption. At around one to two seconds, users begin to notice some delay.

What is the format of REST API response?

When you send a REST request, the appliance responds with a structured response in JSON format. The exact structure of the response depends on the resource and URI of the request, but all responses are similar. The response includes all available resources from any point within the API.


1 Answers

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

like image 155
Mauro Baraldi Avatar answered Oct 04 '22 15:10

Mauro Baraldi