Giter Club home page Giter Club logo

api-response-bundle's Introduction

mattjanssen/api-response-bundle

Latest Version on Packagist Software License Build Status

mattjanssen/api-response-bundle is a slightly-opinionated Symfony bundle for transforming controller action returns and exceptions into a standardized JSON response. The serializer and CORS headers can be configured globally, per path, and per action via annotation.

Install

Via Composer

$ composer require mattjanssen/api-response-bundle

Enable

Enable the bundle in the kernel:

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = [
        // ...
        new MattJanssen\ApiResponseBundle\ApiResponseBundle(),
    ];
}

Configure

api_response:
    defaults:
        serializer: json_encode
        serialize_groups: []
        cors_allow_origin_regex: https://.*\.mydomain\.com
        cors_allow_headers: [Authorization, Content-Type]
        cors_max_age: 86400
    paths:
        somename:
            prefix: /api/v1/
            serializer: jms_serializer
        othername:
            pattern: ^/api/v[2-4]/
            cors_allow_origin_regex: .*

The serializer can be empty, 'array', 'json_encode', 'json_group_encode', 'jms_serializer', or the name of a service which must implement the SerializerAdapterInterface. It defaults to 'json_encode'.

Usage

In your API controllers, just return whatever you want serialized in the response. The ApiResponseBundle takes care of turning that into an actual JSON response.

return [
    'id' => 5,
    'school' => $school,
    'users' => $users,
];

This would result in the following JSON return:

{
    data: {
        id: 5,
        school: ...,
        users: [ ... ]
    },
    error: null
}

Status Codes

By default, responses are sent with the 200 OK status. In order to use a different status, use the @ApiResponse annotation on the controller action. This should only be used to change the success status codes. See the Error Response section for handling error output.

/**
 * @ApiResponse(httpCode=201)
 */
public function createAction() {}

The resulting response would have the 201 CREATED status.

Error Response

To respond with an error, throw any exception implementing the ApiResponseExceptionInterface. On the exception you can optionally set the HTTP status code, the exception code, the exception message and the error data to be serialized into the response.

throw (new ApiResponseException())
    ->setHttpStatusCode(404)
    ->setCode(100404)
    ->setMessage('Could not find school.')
    ->setErrorData(['schoolId' => 42]);

This would result in the following JSON return with a 404 HTTP status:

{
    data: null,
    error: {
        code: 100404,
        message: 'Could not find school.',
        errorData: {
            schoolId: 42
        }
    }
}

Exception Handling

Besides turning ApiResponseExceptionInterface exceptions into error responses, the bundle will also handle any uncaught exceptions in the following manner:

HttpExceptionInterface

The exception status code is used for both the response HTTP code and the error code. The error message is the corresponding Response::$statusTexts array value. Error data is null.

AuthenticationException

Both the response HTTP code and the error code are 401. The error message is "Unauthorized". Error data is null.

AccessDeniedException

Both the response HTTP code and the error code are 403. The error message is "Forbidden". Error data is null.

All Other Exceptions

Both the response HTTP code and the error code are 500.

If the Symfony kernel is not in debug mode, the error message is "Internal Server Error". Error data is null.

If the Symfony kernel is in debug mode, the error message is compiled from the exception class, message, file and line number. And the error data is the exception trace.

Testing

$ composer install --dev
$ vendor/bin/phpunit

License

The MIT License (MIT). Please see License File for more information.

api-response-bundle's People

Contributors

douglaslinsmeyer avatar karim-elshendy avatar mattjanssen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.