Skip to content

API Response

There is a pre-set API response format which is used to format the response. We can either paginate the response or not.

Paginated API Response

Response Format function requires data and pagination as a parameter to send the response.

respondWithPagination(res, data, pagination){
    return res.status(http.StatusCodes.OK).send(responseFormat(data, pagination));
}

Note: Explanation of http.StatusCodes will be explained in the section below.

Above function results into following API response format. We can configure the format by changing the responseFormat function declaration:

{
    "meta": {
        "api": {
            "version": "1.1"
        },
        "pagination": {
            "perPage": 20,
            "page": 1,
            "totalRows": 6,
            "totalPage": 1
        }
    },
    "data": [
        {
            // data
        },
        {
            // data
        },
    ]
}

Non Paginated API Response

Response Format function requires only data as a parameter to send the response.

respondWithOutPagination(res, data){
return res.status(http.StatusCodes.OK).send(responseFormat(data));
}

Above function results to the following API response:

{
    "meta": {
        "api": {
            "version": "1.1"
        }
    },
    "data": {
        // data
    }
}

Error Response

In case of error response will be as shown below.

{
    "meta": {
        "api": {
            "version": 1.1
        }
    },
    "errors": [
        {
            "code": 404,
            "title": "Data not found",
            "detail": "Data not found"
        }
    ]
}

HTTP Response Status Code

Instead of using static HTTP codes, we use http-status-code npm package to send the status code response.

No Content

For no content (204) code we use http.StatusCodes.NO_CONTENT.

noContent(res){
        return res.status(http.StatusCodes.NO_CONTENT).send({});
}

OK

For OK (200) code we use http.StatusCodes.OK.

repondOk(res){
    return res.status(http.StatusCodes.OK).send({});
}

More about HTTP response Status codes