PHP JSON Response Builder: Compose an HTTP response dynamically in JSON

Recommend this page to a friend!
  Info   View files Documentation   View files View files (15)   DownloadInstall with Composer Download .zip   Reputation   Support forum (1)   Blog (1)    
Last Updated Ratings Unique User Downloads Download Rankings
2021-05-31 (3 months ago) RSS 2.0 feedNot enough user ratingsTotal: 111 All time: 9,380 This week: 259Up
Version License PHP version Categories
json-response-builde 1.0.0GNU General Publi...5HTTP, PHP 5
Description Author

This package can compose an HTTP response dynamically in JSON.

It can set the parameters with the given names of a response by assigning the values that should be returned as part of the current HTTP request.

The class can generate the composed response in JSON format and return a string that should be outputted as the response for the current HTTP request.

Innovation Award
PHP Programming Innovation award nominee
May 2021
Number 5
JSON is nowadays a popular format to return the response of requests sent to APIs.

This package can simplify the generation of HTTP responses for APIs that return the responses in JSON format.

Manuel Lemos
Picture of Ahmed Saad
  Performance   Level  
Name: Ahmed Saad <contact>
Classes: 5 packages by
Country: Egypt Egypt
Age: ???
All time rank: 256725 in Egypt Egypt
Week rank: 590 Up12 in Egypt Egypt Up
Innovation award
Innovation award
Nominee: 3x

Details

<p align="center">

<img src="https://laravel.com/assets/img/components/logo-laravel.svg">
<h1 align="center">Json Response Builder Package</h1>

</p>

<p align="center"> <a href="https://travis-ci.org/ahmad-sa3d/json-response-builder"><img src="https://travis-ci.org/ahmad-sa3d/json-response-builder.svg?branch=master" alt="Build Status"></a> <a href="https://codeclimate.com/github/ahmad-sa3d/json-response-builder/maintainability"><img src="https://api.codeclimate.com/v1/badges/84d709814a320dc85f0a/maintainability" /></a> <a href="https://codeclimate.com/github/ahmad-sa3d/json-response-builder/test_coverage"><img src="https://api.codeclimate.com/v1/badges/84d709814a320dc85f0a/test_coverage" /></a> <a href="https://packagist.org/packages/saad/json-response-builder"><img src="https://poser.pugx.org/laravel/framework/license.svg" alt="License"></a> </p>

Install

	composer require saad/json-response-builder

Change Log

> V 1.3.1

add feature to merge meta when adding data

addData(str $key, mix $val, bool $merge_meta)

		
	$builder = new Saad\JsonResponseBuilder\JsonResponseBuilder();
	
	$builder->addData('users', [
		['name' => 'Ahmed Saad'],
		'meta' => [
			'name' => 'iam meta',
		]
	], true); // Note the third argument
	
	
	return $builder->getResponse();
	
	// Output
	
	{
        "success": true,
	
        "meta" : {
            'name' => 'iam meta',
        },
	
        "data": [
            'users': [
            		{"name": "Ahmed Saad"}
            ],
        ],
	
        "message": "Successfully Retrieved"
    }

> V 1.3

Add Strict Mode and enabled by default: in strict mode if data or meta are empty it will set it's value to null instead of []

to turn of strickt mode, on constructor pass false to disable strickt mode so that it will return data, and meta as empty array if they are empty

you can set mode on instance by the method strictMode(bool)


Usage

  • Basic Example:

    inside your controller:

    
    	$builder = new Saad\JsonResponseBuilder\JsonResponseBuilder();
    
    	$builder->mergeData([
    		['name' => 'Ahmed Saad'],
    		['name' => 'John Doe']
    	]);
    
    	$builder->addMeta([
    		'pagination' => [
    			'page' => 1,
    			'per_page' => 4,
    		]
    	]);
    
    	return $builder->getResponse();
    
    
  • the above example will output:

    
    	{
    		"success": true,
    
    		"meta" : {
    			"pagination": {
    				"page": 1,
    				"per_page": 4
    			}
    		},
    
    		"data": [
    			{"name": "Ahmed Saad"},
    			{"name": "John Doe"}
    		],
    
    		"message": "Successfully Retrieved"
    	}
    
    

Available Methods

addData($key, $value)

> Appends to data new member with the given key and value > > ` php > $builder->addData('doctors', ['ahmed', 'mohamed', 'saad']); > $builder->addData('patients', ['patient1', 'patient3', 'patient3']); > > // Output data will be > > "data": { > "doctors": ["ahmed", "mohamed", "saad"], > "patients" ["patient1", "patient4", "patient3"] > }, > > > `

mergeData($array)

> merge given array with data with given array keys as keys, this is usefull when we want to send data as json array insteadof json object with key and value > > this method also if the given array has key called 'meta' it will remove that key and add it to response meta > > ` php > $builder->mergeData(['ahmed', 'mohamed', 'meta' => ['key' => 'Iam Meta']]); > > // Output will be > > { > "success": true, > "meta": { > "key": "Iam Meta" > }, > "data": [ > "ahmed", > "mohamed" > ], > "message": "Successfully Retrieved" > } > > `

addMeta($key, $value)

> Appends to meta new member with the given key and value

mergeMeta($array)

> merge given array with meta

addHeader($header, $value)

> add header to response headers

success($response_message = null)

> set response success status to __true__, and set response message if supplied.

setMessage($response_message = null)

> set response message if supplied.

error($message = null, $error_code = null)

> set response success status to __false__ and set nessage and error code > > ` php > $builder->error('Fails!', 2345); > > // Output will be > > { > "success": false, > "meta": null, > "data": null, > 'error': { > "message": "Fails!", > "code": 2345 > } > "message": "Fails!" > }

addError($key, mixed $value)

> Add key to error array > > ` php > $builder->error('Fails!', 2345) > ->addError('validation', 'validation value'); > > // Output will be > > { > "success": false, > "meta": null, > "data": null, > 'error': { > "message": "Fails!", > "code": 2345, > "validation": "validation value" > } > "message": "Fails!" > }

setStatusCode(301)

> set response status code.

strictMode(bool)

> default value true > > since V1.3 > > enable or disable strict mode. > > ` php > $builder->getResponse(); > > // Strict Mode Enabled, Output will be > > { > "success": false, > "meta": null, > "data": null, > "message": "" > } > > $builder->strictMode(false)->getResponse(); > > // Strict Mode Disabled, Output will be > > { > "success": false, > "meta":[], > "data":[], > "message": "" > }

getResponse($status_code = null)

> set response status code if supplied, and return Response Object

License

The Laravel framework is open-sourced software licensed under the MIT license.README.md

  Files folder image Files  
File Role Description
Files folder image.idea (5 files)
Files folder imagesrc (2 files, 1 directory)
Files folder imagetests (1 directory)
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file composer.lock Data Auxiliary data
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  .idea  
File Role Description
  Accessible without login Plain text file json-response-builder.iml Data Auxiliary data
  Accessible without login Plain text file misc.xml Data Auxiliary data
  Accessible without login Plain text file modules.xml Data Auxiliary data
  Accessible without login Plain text file php.xml Data Auxiliary data
  Accessible without login Plain text file vcs.xml Data Auxiliary data

  Files folder image Files  /  src  
File Role Description
Files folder imageContracts (1 file)
  Plain text file ApiFormRequest.php Class Class source
  Plain text file JsonResponseBuilder.php Class Class source

  Files folder image Files  /  src  /  Contracts  
File Role Description
  Plain text file JsonResponseBuilderContract.php Class Class source

  Files folder image Files  /  tests  
File Role Description
Files folder imageunit (2 files)

  Files folder image Files  /  tests  /  unit  
File Role Description
  Plain text file BuilderTestSetup.php Class Class source
  Plain text file TestJsonResponseBuilder.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:111
This week:0
All time:9,380
This week:259Up
User Comments (1)
Thats a very good class ;-)
3 months ago (Josť Filipe Lopes Santos)
70%StarStarStarStar
 
For more information send a message to info at phpclasses dot org.