Giter Club home page Giter Club logo

api-problem's Introduction

Travis Installs Packagist

Api Problem

This package provides a RFC7807 Problem details implementation. It can be integrated everywhere in your code and should result in a general error response format for HTTP APis.

This package only provides a generic interface, an exception class and some built-in api problem messages. Since handling the exceptions is up to the framework, here is a list of known framework integrations:

Installation

composer require phpro/api-problem

Usage

This package provides a general interface for creating ApiProblem value objects.

use Phpro\ApiProblem\Exception;

throw new ApiProblemException(
    new HttpApiProblem(418, ['detail' => 'Did you know 4,000 people are injured by teapots every year?!'])
);

Built-in problems

ExceptionApiProblem

Debuggable: The exception part will only be added in debug context!

use Phpro\ApiProblem\Http\ExceptionApiProblem;

new ExceptionApiProblem(new \Exception('message', 500));
{
  "status": 500,
  "type": "http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec10.html",
  "title": "Internal Server Error",
  "detail": "message",
  "exception": {
    "message": "message",
    "type": "RuntimeException",
    "code": 500,
    "line": 23,
    "file": "exception.php",
    "trace": [
         "#0 [internal function]: ...",
         "#1 [internal function]: ...",
         "#3 [internal function]: ...",
         "..."
    ],
    "previous": [
      {
        "message": "previous",
        "type": "InvalidArgumentException",
        "code": 0,
        "line": 20,
        "file": "exception.php",
        "trace": [
            "#0 [internal function]: ...",
            "#1 [internal function]: ...",
            "#3 [internal function]: ...",
            "..."
        ]
      }
    ]
  }
}

ForbiddenProblem

use Phpro\ApiProblem\Http\ForbiddenProblem;

new ForbiddenProblem('Not authorized to access gold.');
{
  "status": 403,
  "type": "http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec10.html",
  "title": "Forbidden",
  "detail": "Not authorized to access gold."
}

HttpApiProblem

use Phpro\ApiProblem\Http\HttpApiProblem;

new HttpApiProblem(404, ['detail' => 'The book could not be found.']);
{
    "status": 404,
    "type": "http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec10.html",
    "title": "Not found",
    "detail": "The book could not be found."
}

NotFoundProblem

use Phpro\ApiProblem\Http\NotFoundProblem;

new NotFoundProblem('The book with ID 20 could not be found.');
{
    "status": 404,
    "type": "http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec10.html",
    "title": "Not found",
    "detail": "The book with ID 20 could not be found."
}

UnauthorizedProblem

use Phpro\ApiProblem\Http\UnauthorizedProblem;

new UnauthorizedProblem('You are not authorized to access X.');
{
    "status": 401,
    "type": "http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec10.html",
    "title": "Unauthorized",
    "detail": "You are not authenticated. Please login."
}

ValidationApiProblem

composer require symfony/validator:^4.1
use Phpro\ApiProblem\Http\ValidationApiProblem;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;

new ValidationApiProblem(new ConstraintViolationList([
    new ConstraintViolation('Invalid email', '', [], '', 'email', '', null, '8615ecd9-afcb-479a-9c78-8bcfe260cf2a'),
]));
{
    "status": 400,
    "type": "https:\/\/symfony.com\/errors\/validation",
    "title": "Validation Failed",
    "detail": "email: Invalid Email",
    "violations": [
        {
            "propertyPath": "email",
            "title": "Invalid email",
            "type": "urn:uuid:8615ecd9-afcb-479a-9c78-8bcfe260cf2a"
        }
    ]
}

Creating your own problem

Creating problem sounds scarry right!? Since the RFC is very loose, we made the interface as easy as possible:

use Phpro\ApiProblem\ApiProblemInterface;

class MyProblem implements ApiProbelmInterface
{
    public function toArray(): array
    {
        return [
            'type' => 'about:blank',
            'status' => '99',
            'title' => 'Got 99 problems but a glitch aint one!',
        ];
    }
}

A lot of problems will be detected in an HTTP context. Therefore, we also provided a base HttpApiProblem class. This one will automatically fill in the type and title section based on the HTTP code. The only thing you'll need to do, is add some additional data to it:

use Phpro\ApiProblem\Http\HttpApiProblem;

class MyProblem extends HttpApiProblem
{
    public function __construct(string $details)
    {
        parent::__construct(500, ['details' => $details]);
    }
}

If you want to log additional information in a debug context, it is possible to implement an additional DebuggableApiProblemInterface:

use Phpro\ApiProblem\DebuggableApiProblemInterface;

class MyProblem implements DebuggableApiProblemInterface
{
    public function toArray(): array
    {
        return [
            'type' => 'about:blank',
            'status' => '99',
            'title' => 'Got 99 problems but a glitch aint one!',
        ];
    }

    public function toDebuggableArray(): array
    {
        return array_merge(
            $this->toArray(),
            [
                'situation' => 'If you are having code problems, I feel bad for you son',
            ]
        );
    }
}

About

Submitting bugs and feature requests

Bugs and feature request are tracked on GitHub. Please take a look at our rules before contributing your code.

License

api-problem is licensed under the MIT License.

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.