Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/pingcheng/api-response-archive

A simple PHP API helper to generate JSON or XML result
https://github.com/pingcheng/api-response-archive

api api-helper php-api restful restful-api

Last synced: about 2 months ago
JSON representation

A simple PHP API helper to generate JSON or XML result

Awesome Lists containing this project

README

        

# api-response
[![Build Status](https://travis-ci.org/pingcheng/api-response.svg?branch=master)](https://travis-ci.org/pingcheng/api-response)
[![Coverage Status](https://coveralls.io/repos/github/pingcheng/api-response/badge.svg?branch=master)](https://coveralls.io/github/pingcheng/api-response?branch=master)

A simple PHP API helper to generate JSON or XML result

# Installation
```bash
composer require pingcheng/api-response
```

# Supproted format
| Format | Support |
| ------------- | ------------- |
| Json | ✅ |
| XML | ✅ |

# Usage

## Basic
```php
use PingCheng\ApiResponse\ApiResponse;

echo ApiResponse::json()
->code(400)
->addProperty('message', [
'your result has been accepted'
])
->data([
'id' => '1234',
'result' => 'accepted'
]);
```

Or
```php
ApiResponse::json()
->code(400)
->addProperty('message', [
'your result has been accepted'
])
->data([
'id' => '1234',
'result' => 'accepted'
])
->send();
// The program will stop by send() and return the result instantly
```
The reuslt you would have
```json
{
"code": 400,
"status": "Bad Request",
"data": {
"id": "1234",
"result": "accepted"
},
"message": [
"your result has been accepted"
]
}
```

Or, if you want to have a XML result
```php
use PingCheng\ApiResponse\ApiResponse;

echo ApiResponse::xml()
->code(400)
->addProperty('message', [
'your result has been accepted'
])
->data([
'id' => '1234',
'result' => 'accepted'
]);
```

the result you would have
```xml

400
Bad Request

1234
accepted

your result has been accepted

```

## Property
- addProperty(name, value);
- removeProperty(name);

Basically, ApiReponse would auto add a status description to the result based on the status code, for example, if you add 200 code to the response, the api would automatically add a status of "OK!". If you need to modify it, please use this function to add it or remove it
```php
// for modify
...
->status('the new status message')
...

// for remove it
...
->removeProperty('status')
...
```

## Headers control
- addHeader(name, value);
- removeHeader(name);
- removeAllHeaders();

## Status shortcuts
You can use short cuts to specific a status code
```php
ApiResponose::json()->success()->send();
```