Skip to content
On this page

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.

protected function respondWithCollection($collection, $callback, $resourceKey)
{
    $paginatedCollection = $collection->getCollection();

    $resource = new Collection($paginatedCollection, $callback, $resourceKey);

    $resource->setPaginator(new IlluminatePaginatorAdapter($collection));

    $rootScope = $this->fractal->createData($resource);

    return $this->metaEncode($rootScope->toArray());
}

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.

protected function respondWithOutPagination($collection, $callback, $resourceKey)
{
    $resource = new Collection($collection, $callback, $resourceKey);
    $rootScope = $this->fractal->createData($resource);

    return $this->metaEncode($rootScope->toArray());
}

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"
        }
    ]
}

More about HTTP response Status codes