PHP code example of tnapf / api-skeleton

1. Go to this page and download the library: Download tnapf/api-skeleton 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/ */

    

tnapf / api-skeleton example snippets




namespace App\Controllers;

use Core\ApiResponse;
use Core\Routing\Route;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Tnapf\Router\Interfaces\ControllerInterface;
use Tnapf\Router\Routing\RouteRunner;

#[Route('/ping', ['GET'])]
class Ping implements ControllerInterface
{
    public function handle(
        ServerRequestInterface $request,
        ResponseInterface $response,
        RouteRunner $route
    ): ResponseInterface {
        return ApiResponse::success();
    }
}



namespace App\Catchers;

use Core\ApiResponse;
use Core\Routing\Catcher;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Tnapf\Router\Exceptions\HttpNotFound;
use Tnapf\Router\Interfaces\ControllerInterface;
use Tnapf\Router\Routing\RouteRunner;

#[Catcher(HttpNotFound::class)]
class E404 implements ControllerInterface
{
    public function handle(
        ServerRequestInterface $request,
        ResponseInterface $response,
        RouteRunner $route
    ): ResponseInterface {
        return ApiResponse::error('Endpoint Not Found', 404);
    }
}

use Core\ApiResponse;ApiResponse;

ApiResponse::success(200);
/**
 * {
 *   "success": true
 * }
 */

ApiResponse::successWithData(['foo' => 'bar']);
/**
 * {
 *   "success": true,
 *   "data": {
 *     "foo": "bar"
 *   }
 * } 
 */

ApiResponse::error('life is pain', 500);
/**
 * {
 *   "success": false,
 *   "message": "life is pain",
 *   "code": 500
 * } 
 */

ApiResponse::errorWithData('life is pain', ['foo' => 'bar'], 500);
/**
 * {
 *    "success": false,
 *    "message": "life is pain",
 *    "code": 500,
 *    "data": {
 *      "foo": "bar"
 *    } 
 * }
 */