PHPackages                             nickjbedford/json-response - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. nickjbedford/json-response

ActiveLibrary[HTTP &amp; Networking](/categories/http)

nickjbedford/json-response
==========================

Defines a uniform JSON response structure for PHP 7.4+ applications.

0.1.3(2y ago)0581MITPHPPHP &gt;=7.4

Since Apr 16Pushed 2y ago1 watchersCompare

[ Source](https://github.com/nickjbedford/json-response)[ Packagist](https://packagist.org/packages/nickjbedford/json-response)[ Docs](https://github.com/nickjbedford/json-response)[ RSS](/packages/nickjbedford-json-response/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (5)Used By (1)

JsonResponse
============

[](#jsonresponse)

The JsonResponse library for PHP defines a simple and uniform structure for JSON API responses, from success status to error information and data payloads.

All keys are guaranteed to exist, even if they are null. This ensures clients of an API do not have to waste time and code checking if standard properties exist before checking their values.

Success Responses
-----------------

[](#success-responses)

To create a **success** response, use either the `\YetAnother\JsonResponse::success()` method or the `json_success()` function.

### Example

[](#example)

```
$response = json_success();

$json = $response->toJSON();
$json = strval($response); // This calls $response->toJSON()

// Create a response with a payload
$personResponse = json_success([
    'id' => 123,
    'name' => 'John Citizen',
    'dob' => '1985-01-01'
]);
```

The basic response structure for a successful request without any data payload is as follows:

```
{
    "success": true,
    "error": null,
    "data": null
}
```

FieldTypeDescription`success`boolean`true` for a successful response, otherwise `false` for an error response.`error`object or `null``null` for successful responses, otherwise a `JsonResponseError` object.`data`mixed or `null`An optional data payload containing any type of data including `null`. This will depend on the API request.Error Responses
---------------

[](#error-responses)

To create a **failure** response, use either the `\YetAnother\JsonResponse::failure()` method or the `json_success()` function.

### Example

[](#example-1)

```
$response = json_failure("Person not found.", "E_NOTFOUND");

$json = $response->toJSON();
```

The basic response structure for a failed request is as follows:

```
{
    "success": true,
    "error": {
        "message": "Some error message...",
        "code": null,
        "data": null
    },
    "data": null
}
```

FieldTypeDescription`error.message`stringAn error message for the client to display to the user.`error.code`string or `null`An optional error code for the client to use in handling the error. This will depend on the API request.`error.data`mixed or `null`Optional information about the error. This may contain debugging information about exceptions thrown by the server if provided.### Exception Error Responses

[](#exception-error-responses)

To create a **failure** response based on an exception, use either the `\YetAnother\JsonResponse::exception()` method or the `json_exception()` function.

### Example

[](#example-2)

```
$exception = new Exception("Database connection was lost.", "E_DBCONN");

$response = json_exception($exception, true); // true to include debugging information

$json = $response->toJSON();
```

The response will contain the following data including the exception debug data:

```
{
    "success": false,
    "error": {
        "message": "Database connection was lost.",
        "code": "E_DBCONN",
        "data": {
            "class": "Exception",
            "file": "/home/user/documents/my-project/example.php",
            "line": 34,
            "trace": ""
        }
    }
}
```

If debugging data is included in the exception response, the `error.data`property will be structured as follows:

FieldTypeDescription`error.data.class`stringThe PHP class name of the exception throw.`error.data.file`stringThe name of the PHP script where the exception occurred.`error.data.file`intThe line number in the PHP script where the exception occurred.`error.data.trace`stringThe stack trace formatted as a string.Record Sets
-----------

[](#record-sets)

To create a standardised response for record set responses with paging information, use the `\YetAnother\JsonResponse::recordSet()` method or `json_records()` function.

### Example

[](#example-3)

```
$records = [ 10, 20, 30, 40, 50 ];

$response = json_records($records, 2, 5, 30, 'Integer');

$json = $response->toJSON();
```

The response will contain the following data:

```
{
    "success": true,
    "error": null,
    "data": {
        "records": [ 10, 20, 30, 40, 50 ],
        "page": 2,
        "pageLength": 5,
        "total": 30,
        "nextPage": 3,
        "previousPage": 1,
        "recordType": "Integer"
    }
}
```

FieldTypeDescription`data.records`arrayAn array containing the page's records.`data.page`intThe zero-based page index for the current record set.`data.pageLength`intThe length of each page in the query.`data.total`intThe total number of records in the query.`data.nextPage`int or `null`The next page's index if there are more records, otherwise `null`.`data.previousPage`int or `null`The previous page's index if the current page index is non-zero, otherwise `null`.`data.recordType`string or `null`An optionally provided name of the type of records in the record set. This is defined by the API using the library.

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~287 days

Total

4

Last Release

993d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8bce7dd852d725a53d2d7a81183acc952c7902242b8fcfa4b45564fe1702d8f3?d=identicon)[nickjbedford](/maintainers/nickjbedford)

---

Top Contributors

[![nickjbedford](https://avatars.githubusercontent.com/u/10795658?v=4)](https://github.com/nickjbedford "nickjbedford (1 commits)")

---

Tags

jsonapirest

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/nickjbedford-json-response/health.svg)

```
[![Health](https://phpackages.com/badges/nickjbedford-json-response/health.svg)](https://phpackages.com/packages/nickjbedford-json-response)
```

###  Alternatives

[serpapi/google-search-results-php

Get Google, Bing, Baidu, Ebay, Yahoo, Yandex, Home depot, Naver, Apple, Duckduckgo, Youtube search results via SerpApi.com

69114.3k](/packages/serpapi-google-search-results-php)[ismaeltoe/osms

PHP library wrapper of the Orange SMS API.

4540.0k](/packages/ismaeltoe-osms)[jsor/hal-client

A lightweight client for consuming and manipulating Hypertext Application Language (HAL) resources.

2425.9k1](/packages/jsor-hal-client)[elao/json-http-form-bundle

Adds support of JSON requests for Forms

356.0k](/packages/elao-json-http-form-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
