api-skeletons/laravel-api-problem

Problem Details for HTTP APIs for Laravel
10,467 11
Install
composer require api-skeletons/laravel-api-problem
Latest Version:2.0.1
PHP:^8.1
License:BSD-3-Clause
Last Updated:Apr 13, 2024
Links: GitHub  ·  Packagist
Maintainer: tom_anderson

API Problem for Laravel

Build Status Code Coverage PHP Version Total Downloads License

This repository implements RFC 7807 "Problem Details for HTTP APIs" for Laravel.

Installation

Run the following to install this library using Composer:

composer require api-skeletons/laravel-api-problem

Quick Start

use ApiSkeletons\Laravel\ApiProblem\Facades\ApiProblem;

return ApiProblem::response('Detailed Unauthorized Message', 401);

This will result in a 401 response with header

Content-Type: application/problem+json

and content

{
    "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
    "title": "Unauthorized",
    "status": 401,
    "detail": "Detailed Unauthorized Messsge"
}

Use

Using the facade

You may use the ApiProblem object in two ways. First, you can use the facade to return a response quickly and directly as shown in the Quick Start. When using the facade the arguments to the response() method are:

response(
    string|Throwable $detail, 
    int|string $status, 
    ?string $type = null, 
    ?string $title = null, 
    array $additional = []
)

Creating an object

When creating an ApiProblem object directly, the first two parameters are swapped. The reason for this is the constructor for the original object remains unchanged and the response() function is modified to match the standard Laravel response format.

__construct(
    int|string $status, 
    string|Throwable $detail, 
    ?string $type = null, 
    ?string $title = null, 
    array $additional = []
)

An example of creating an object directly:

use ApiSkeletons\Laravel\ApiProblem\ApiProblem;

$apiProblem = new ApiProblem(401, 'Detailed Unauthorized Message');
return $apiProblem->response();

Additional Details

The 5th parameter to ApiProblem is $additional. This array adds adhoc properties to the JSON response. One method of using this array is a 422 response with details of the problem:

use ApiSkeletons\Laravel\ApiProblem\Facades\ApiProblem;
use Illuminate\Validation\ValidationException;

try {
    $validated = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);
} catch (ValidationException $e) {
    return ApiProblem::response($e->getMessage(), 422, null, null, ['errors' => $e->errors()]);
}

results in:

{
    "errors":{
        "title":[
            "The title field is required."
        ],
        "body":[
            "The body field is required."
        ]
    },
    "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
    "title": "Unprocessable Entity",
    "status": 422,
    "detail": "The given data was invalid."
}

Use with the Exception Handler

namespace App\Exceptions;

use ApiSkeletons\Laravel\ApiProblem\Facades\ApiProblem;
use Doctrine\ORM\EntityNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Request;

class Handler extends ExceptionHandler
{
    public function register(): void
    {
        $this->renderable(function (EntityNotFoundException $e, Request $request) {
            return ApiProblem::response($e->getMessage(), 404);
        });
    }
}

Attribution

The bulk of this repository was copied from Laminas API Tools. I wanted to provide a simplified interface specific to Laravel. Though the tool could have been used directly from the Laminas library it would have come with a lot of overhead.

Related Packages

marcelgwerder/laravel-api-handler

Package providing helper functions for a Laravel REST-API

94,344 155
threesquared/laravel-wp-api

Laravel package for the Wordpress JSON REST API

10,364 13
pixelpeter/laravel5-woocommerce-api-client

Laravel 5 wrapper for the Woocommerce REST API

106,676 123
vjroby/laravel-nonce

This is a package for integrating nonces in Laravel in requests

42,757 3
sdv/laravel-endpoint

Laravel Endpoint is a CRUD REST API package for Laravel.

18,791 11