PHP code example of ayd / api-response-base

1. Go to this page and download the library: Download ayd/api-response-base library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ayd / api-response-base example snippets


use Ayd\ApiResponseBase\Response;
use Ayd\ApiResponseBase\StatusCode;

// Using convenience methods
$response = Response::ok($data);
$response = Response::created($data, 'Resource created');
$response = Response::noContent();

// Error responses
$response = Response::badRequest('Invalid input', $errors);
$response = Response::unauthorized();
$response = Response::forbidden();
$response = Response::notFound('User not found');
$response = Response::unprocessable('Validation failed', $errors);
$response = Response::internalError();

// Custom status code
$response = Response::build(StatusCode::CREATED, $data, 'Created');
$response = Response::build(418, null, "I'm a teapot");

use Ayd\ApiResponseBase\Meta;

// Create with static factories
$meta = Meta::requestId('custom-id');
$meta = Meta::abilities(['create' => true, 'delete' => false]);
$meta = Meta::pagination(total: 100, perPage: 20, currentPage: 1);

// Immutable setters
$meta = $meta->withAbilities(['edit' => true]);
$meta = $meta->withRequestId('another-id');

// Merge two Meta objects (the other wins on conflict)
$merged = $paginationMeta->merge($abilitiesMeta);

// Works with both Laravel's and Hyperf's paginator
$response = Response::ok($paginator);

$meta = Meta::fromPaginator($paginator); // duck-typed
$meta = Meta::pagination(total: 50, perPage: 10, currentPage: 2);

use Ayd\ApiResponseBase\Contracts\AbilitiesResolver;

class MyAbilitiesResolver implements AbilitiesResolver
{
    public function resolve(mixed $user = null): array
    {
        return [
            'create' => $user?->can('create') ?? false,
            'delete' => $user?->can('delete') ?? false,
        ];
    }
}

use Ayd\ApiResponseBase\Concerns\BuildsApiResponse;

class MyService
{
    use BuildsApiResponse;

    public function handle()
    {
        $meta = $this->buildMeta();        // auto-generates request_id, auto-resolves abilities
        $meta = $this->resolveAbilitiesMeta($user); // resolve for a specific user
    }
}

use Ayd\ApiResponseBase\StatusCode;

StatusCode::OK;                 // 200
StatusCode::CREATED;            // 201
StatusCode::ACCEPTED;           // 202
StatusCode::NO_CONTENT;         // 204
StatusCode::BAD_REQUEST;        // 400
StatusCode::UNAUTHORIZED;       // 401
StatusCode::FORBIDDEN;          // 403
StatusCode::NOT_FOUND;          // 404
StatusCode::UNPROCESSABLE_ENTITY; // 422
StatusCode::INTERNAL_SERVER_ERROR; // 500