PHP code example of rodrigoaramburu / php-json-server

1. Go to this page and download the library: Download rodrigoaramburu/php-json-server 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/ */

    

rodrigoaramburu / php-json-server example snippets


$server = new Server([
    'database-file' => __DIR__.'/database.json',
]);

$path = $_SERVER['REQUEST_URI'];
$body = file_get_contents('php://input');
$headers = getallheaders();
$response = $server->handle($_SERVER['REQUEST_METHOD'], $path, $body, $headers);

$server->send($response);

use DI\Container;
use JsonServer\Server;
use Slim\Factory\AppFactory;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

$container = new Container();
AppFactory::setContainer($container);
$app = AppFactory::create();

$server = new Server([
    'database-file' => __DIR__.'/database.json',
]);

$app->any('/api/{path:.*}' , function(RequestInterface $request, ResponseInterface $response, $args) use($server){
     
    $path = '/'.$args['path'];
    $body = (string) $request->getBody();
    $headers = $request->getHeaders();
    $response = $server->handle($request->getMethod(), $path, $body, $headers);
    
    return $response;
});
 
$app->run();
 
use JsonServer\Middlewares\Handler;
use JsonServer\Middlewares\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class ExampleMiddleware extends Middleware
{
    public function process(ServerRequestInterface $request, Handler $handler): ResponseInterface
    {
        //antes de ser processado
        $authToken = $request->getHeader("Authorization");
        
        $response = $handler->handle($request);
        
        // após ser processado 
        $response = $response->withHeader('Content-Type','application/json');
        return $response;
    }
}

$server->addMiddleware(new ExampleMiddleware());

$staticRoutes = new StaticMiddleware([
    "/static/route" => [
        "GET" => [
            "body" => "{\"message\": \"Uma resposta GET para o cliente \"}",
            "statusCode" => 200,
            "headers" => [
                "Content-Type" => "application/json"
            ]
        ],
        "POST" => [
            "body" => "{\"message\": \"Uma resposta POST para o cliente\"}",
            "statusCode" => 201,
            "headers" => [
                "Content-Type" => "application/json"
            ]
        ],
    ]
]);
$server->addMiddleware($staticRoutes);

$staticRoutes = new StaticMiddleware(__DIR__.'/static.json');
$server->addMiddleware($staticRoutes);
shell
php -S localhost:8000 index.php