Simple and ready to use API response wrapper for Laravel.

Overview

Laravel API Response

Build Status StyleCI Packagist Packagist Version

Simple Laravel API response wrapper.


API response code sample

Installation

  1. Install the package through composer:

    $ composer require obiefy/api-response

  2. Register the package service provider to the providers array in app.php file:

    Obiefy\API\ApiResponseServiceProvider::class

  3. Register the package facade alias to the aliases array in app.php file:

    'API' => Obiefy\API\Facades\API::class,

  4. And finally you can publish the config file:

    php artisan vendor:publish --tag=api-response

Note: You could also include "use Obiefy\API\Facades\API;" at the top of the class, but we recommend not to.

Basic usage

There are to ways of utilizing the package: using the facade, or using the helper function. On either way you will get the same result, it is totally up to you.

Facade:

use API;

...

public function index()
{
    $users = User::all();

    return API::response(200, 'users list', $users);
}

Note: If you decide not to register the service provider and the facade, alias then you need to include use Obiefy\API\Facades\API; at the top of the class, but we recommend not to.

Helper function:

public function index()
{
    $users = User::all();

    return api()->response(200, 'users list', $users);
}

Advanced usage

The response() method accepts three mandatory parameters:

  • int $status
  • string $message
  • string | array $data

For example, in the below example we are calling the response() method thru the facade and we are passing the following parameters: 200 as the status code, User list as the message and $users (a collection of users) as the data.

use API;

...

public function index()
{
    $users = User::all();

    return API::response(200, 'Users list', $users);
}

This is the result:

{
    "STATUS": 200,
    "MESSAGE": "Users list",
    "DATA": [
        {"name": "Obay Hamed"}
    ]
}

If you need more data other than the defaults STATUS, MESSAGE, and DATA attributes on your json response, you could pass as many parameters as you need after $data. However, we do recommend formating the extra parameters as a $key => $value array.

As you can see in the below example, we are calling the api() helper and we are passing the following parameters: 200 as the status code, User list as the message, $users (a collection of users) as the data, $code as a key value array and $error as another key value array.

public function index()
{
    $users = User::all();
    $code = ['code' => 30566];
    $error = ['reference' => 'ERROR-2019-09-14'];

    return api()->response(200, 'Users list', $users, $code, $error);
}

This is the result:

{
    "STATUS": 200,
    "MESSAGE": "Users list",
    "DATA": [
        {"name": "Obay Hamed"}
    ],
    "code": 30566,
    "error": "ERROR-2019-09-14"
}

Another way of creating a response is by calling api() method and passing the parameters directly to the helper function. Again, it is up to you how you better want to use it.

Check the below code example.

public function index()
{
    $users = User::all();

    return api(200, 'Users list', $users);
}

This is the result:

{
    "STATUS": 200,
    "MESSAGE": "users list",
    "DATA": [
        {"name": "Obay Hamed"}
    ]
}

Helper functions

The package ships with a group of functions that will help you to speed up your development process. For example, you could call directly api()->ok() if the response was successful, instead of building the response.

function ok()

The ok() function can be used without passing any parameters, it will defaulted the status code to 200 and use the default message from the configuration file.

return api()->ok();

Result:

{
    "STATUS": 200,
    "MESSAGE": "Process is successfully completed",
    "DATA": {}
}

Or you could pass to the function a custom message and the data you need. In this case, as mentioned before, the ok() status code will be defaulted to 200.

$users = User::all();

return api()->ok("User list", $users);

Result:

{
    "STATUS": 200,
    "MESSAGE": "User list",
    "DATA": [
        {"name": "Obay Hamed"}
    ]
}

function notFound()

The notFound() function, as its name states, should be used for the case when the resource is not found and the status code will be defaulted to 404. You could pass a custom message to this function otherwise it will use the default message from the configuration file.

return api()->notFound();

function validation()

The validation() function can be used on the case of a validation error exist, throwing a 422 status code by default. It accepts two mandatory parameters: a message and an array of errors, and as many extra parameters you need (we recommend a key value array format). If the message is empty, then the default message will be used instead.

return api()->validation('These fields are required.', ['name', 'lastName']);

function error()

The error() function can be used when an internal server error occurs throwing a 500 status code by default. It accepts two mandatory parameters: a message and an array of errors, and as many extra parameters you need (we recommend a key value array format). If the message is empty, then the default message will be used instead.

Configuration

JSON Response Labels

If you need to customize the default messages or the json response labels, you can do it directly on the api.php configuration file.

method default status code change code message
ok() 200 config('api.codes.success) config('api.messages.success)
notFound() 404 config('api.codes.notfound) config('api.messages.notfound)
validation() 422 config('api.codes.validation) config('api.messages.validation)
error() 500 config('api.codes.error) config('api.messages.error)

Matching Status Codes

By default, all API responses return a 200 OK HTTP status header. If you'd like the status header to match the Response's status, set the matchstatus configuration to true

Include The Count Of Data

You can optionally include the count of the DATA portion of the response, by setting includeDataCount to true in the api.php configuration file. You can also override the label, if desired, by updating the label in thekeys array of the configuration file.

{
    "STATUS": "200",
    "MESSAGE": "User Profile data",
    "DATA": [
        ...
    ],
    "DATACOUNT": 6
}

Contributing

We will be happy if we see PR from you.

License

The API Response is a free package released under the MIT License.

Comments
  • Adds data count to the response

    Adds data count to the response

    • appends the dataCount for $data that is countable and not empty
    • Adds configuration
      • configurable label for dataCount, defaulting to "DATACOUNT"
      • optionally includes the dataCount, defaulting to false
    • Updates to the README
      • Adds configuation sections
      • Adds information about matching Status codes (#16)
      • updates validation status code to 422 to match the changes introduced in fd90e10
      • Adds data count feature
    opened by beauraines 11
  • Add ability to make response parameters flexible

    Add ability to make response parameters flexible

    I thinking about something like this.

    api()->response($status, $message, $data, $extraData);
    

    at the current version this will not work, because response() method parameters are fixed to three (status, message and data).

    enhancement 
    opened by obiefy 6
  • Add support for extra data passed thru the response function

    Add support for extra data passed thru the response function

    The extra data can be added as a single array or as many arrays. The extra data is recommended to be added as an array otherwise it will be added as 0 => data, 1 => data.

    Let me know if this works for you and if I can proceed to add the new feature to the rest of the responses functions such as ok(), validation(), etc

    Cheers

    opened by SamyOteroGlez 5
  • Installation Issue

    Installation Issue

    I am having

    Problem 1
       - Installation request for obiefy/api-response ^0.9.1 -> satisfiable by obiefy/api-response[v0.9.1].
       - Installation request for laravel/framework (locked at v8.10.0, required as ^8.0) -> satisfiable by laravel/framework[v8.10.0].
       - Can only install one of: laravel/framework[8.x-dev, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.0.0, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.0.1, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.0.2, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.0.3, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.0.4, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.1.0, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.10.0, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.2.0, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.3.0, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.4.0, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.5.0, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.6.0, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.7.0, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.7.1, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.8.0, 5.7.x-dev].
       - Can only install one of: laravel/framework[v8.9.0, 5.7.x-dev].
       - Can only install one of: laravel/framework[5.7.x-dev, v8.10.0].
       - Can only install one of: laravel/framework[5.7.x-dev, v8.10.0].
       - Conclusion: install laravel/framework 5.7.x-dev
       - Installation request for laravel/framework ^8.0 -> satisfiable by laravel/framework[8.x-dev, v8.0.0, v8.0.1, v8.0.2, v8.0.3, v8.0.4, v8.1.0, v8.10.0, v8.2.0, v8.3.0, v8.4.0, v8.5.0, v8.6.0, v8.7.0, v8.7.1, v8.8.0, v8.9.0].
    

    How can I fix it?

    opened by UtkuDalmaz 4
  • Add status code to json response

    Add status code to json response

    Tested with postman. If: return api()->response(418, 'I am a teapot', ''); then the http response will have the status code like 200 OK and the response body will contain (as expected):

    {
        "STATUS": "418",
        "MESSAGE": "I am a teapot",
        "DATA": ""
    }
    

    with the new addition, the status http response status code will be 418 I'm a teapot and the response body will be the same.

    opened by SamyOteroGlez 4
  • Move messages to translation files

    Move messages to translation files

    In order to have a clean structure for messages, I though it may be a good idea to move all available default messages to a better place like Laravel languages and give the ability to user so as to customize them.

    All tests are passed.

    opened by Mdhesari 3
  • Compatibility with Laravel 8

    Compatibility with Laravel 8

    I am trying to install it on Laravel 8.6 but i get:

    Problem 1 - Installation request for obiefy/api-response ^0.9.1 -> satisfiable by obiefy/api-response[v0.9.1]. - Conclusion: remove laravel/framework v8.6.0 - Conclusion: don't install laravel/framework v8.6.0

    Any idea if this a compatibility issue with the latest Laravel 8?

    opened by tsangaris 3
  • Type cast DATACONT to string

    Type cast DATACONT to string

    if the config('api.stringify') is set to true response will be like:

    {
        "STATUS": "200",
        "MESSAGE": "User Profile data",
        "DATA": [
            ...
        ],
        "DATACOUNT": 6
    }
    

    The expected response is:

    {
        "STATUS": "200",
        "MESSAGE": "User Profile data",
        "DATA": [
            ...
        ],
        "DATACOUNT": "6"
    }
    

    @beauraines can you please submit PR for this one?

    opened by obiefy 2
  • The API response doesn't set the http status header

    The API response doesn't set the http status header

    It seems that all of your API responses return a 200 OK http status header.

    This means that any receiving front-end framework will receive conflicting status information in the event of a non-200 status (JSON object says "500 Internal Server Error", http header says "200 OK") and front-end libraries may fail to detect errors as the status header tells them everything's OK, even if the server has thrown an error.

    Screenshot 2019-09-30 at 17 21 40

    opened by Steve-MP 2
  • Support JSON API specification

    Support JSON API specification

    It would be good if you could support and promote use of the JSON API specification, which is already an established format:

    HTTP/1.1 422 Unprocesssable Entity
    Content-Type: application/vnd.api+json
    
    {
      "errors": [
        {
          "source": { "pointer": "" },
          "detail":  "Missing `data` Member at document's top level."
        }
      ]
    }
    

    https://jsonapi.org/examples/

    opened by aalaap 2
  • PHP 8 Compatibility

    PHP 8 Compatibility

    Hello developer, I'm using your excellent package, but I have a issue with php 8 version, can you update your package to fix this problem?.

    This is composer console error:

    Problem 1 - Root composer.json requires obiefy/api-response ^0.9.5 -> satisfiable by obiefy/api-response[v0.9.5]. - obiefy/api-response v0.9.5 requires php ^7.3 -> your php version (8.0.5) does not satisfy that requirement.

    Thanks!!

    opened by marcoscoolnumber9 1
Releases(v0.9.7)
Owner
Obay Hamed
Technical Lead, Software Engineer 👨‍💻
Obay Hamed
Simple package to handle response properly in your API.

Simple package to handle response properly in your API. This package uses Fractal and is based on Build APIs You Won't Hate book.

Optania 375 Oct 28, 2022
Convert remote api response data into laravel model

laravel remote model Create remote driver to convert remote api request into laravel model. 中文文档 日本語文書 overview Install the version between laravel5.5

张子彬 15 Aug 11, 2022
Simple PSR-7 compatible response sender

Simple PSR-7 compatible response sender

Lazzard 4 Nov 5, 2022
Easily capture every incoming request and the corresponding outgoing response in your Laravel app.

Easily capture every incoming request and the corresponding outgoing response in your Laravel app. This package is designed to work only with the Lara

Mark Townsend 22 Nov 15, 2022
A nice GUI for Laravel Artisan, ready out of the box, configurable and handy for non-CLI experienced developers.

Artisan UI A nice GUI for Laravel Artisan, ready out of the box, configurable and handy for non-CLI experienced developers. Supported commands must be

Pablo Leone 1 Dec 3, 2021
A Laravel Wrapper for the CoinDCX API. Now easily connect and consume the CoinDCX Public API in your Laravel apps without any hassle.

This package provides a Laravel Wrapper for the CoinDCX API and allows you to easily communicate with it. Important Note This package is in early deve

Moinuddin S. Khaja 2 Feb 16, 2022
This Package helps you in laravel application to log all desired activity for each request from request entry point to generate response at a single snapshot.

Laravel Scenario Logger This Package helps you in laravel application to log all desired activity for each request from request entry point to generat

Mehrdad Mahdian 6 Sep 27, 2021
A Laravel response helper methods.

A Laravel response helper methods. The package respond provides a fluent syntax to form array or json responses.

Najm Njeim 5 Nov 2, 2021
Provides a powerful error response system for Laravel

Laravel Exceptions Laravel Exceptions was created by, and is maintained by Graham Campbell, and provides a powerful error response system for both dev

Graham Campbell 571 Jan 31, 2022
Laravel Custom Response Messages from Passport Oauth2 Server

This is a sample repository showing how to install Oauth2 server using Laravel's passport package and customize its responses.

M. Ismail 7 Nov 22, 2022
Laravel Response Formatter

I created this package to make it easier to format the response from a controller. I have used this package in my projects and I hope you enjoy it!

aris wahyudiyanto 12 Dec 5, 2022
📦 Flatpack: Administration panel for Laravel, ready to assemble.

Flatpack ?? Administration panel for Laravel, ready to assemble. Quickly create CRUD (Create, Read, Update, Delete) interfaces for your Eloquent model

Flatpack 10 Sep 16, 2022
A Magento Incident Response Plan Template

A Magento centric Incident Response Plan Template Introduction This will provide you with our defined process and procedures to use when responding to

Talesh Seeparsan 75 Dec 30, 2022
A simple API wrapper to Gigapay's APIs for Laravel Framework

Laravel-Gigapay A simple API wrapper for Gigapay's APIs. It gives you helper methods that will make your work with gigapay's API easy, fast and effici

Asif Patel 3 May 23, 2022
Laravel wrapper to use Lightship PHP

lightship-laravel Laravel wrapper to use Lightship PHP. Summary About Features Installation Examples Tests About Lightship is a way to get web page au

Lightship 3 Dec 11, 2022
A super simple package allowing for use MySQL 'USE INDEX' and 'FORCE INDEX' statements.

Laravel MySQL Use Index Scope A super simple package allowing for use MySQL USE INDEX and FORCE INDEX statements. Requirements PHP ^7.4 | ^8.0 Laravel

Vasyl 29 Dec 27, 2022
A simple to use query builder for the jQuery QueryBuilder plugin for use with Laravel.

QueryBuilderParser Status Label Status Value Build Insights Code Climate Test Coverage QueryBuilderParser is designed mainly to be used inside Laravel

Tim Groeneveld 149 Nov 11, 2022
Mollie API client wrapper for Laravel & Mollie Connect provider for Laravel Socialite

Mollie for Laravel Laravel-Mollie incorporates the Mollie API and Mollie Connect into your Laravel or Lumen project. Accepting iDEAL, Apple Pay, Banco

Mollie 289 Nov 24, 2022
Laravel wrapper package for the Aimon.it API

Laravel Aimon Package A laravel wrapper package for the Aimon.it API. For more information see Aimon Requirements Laravel 6 or later Installation Inst

Ruslan 3 Aug 7, 2022