restyphp/resty

This package is abandoned and no longer maintained. No replacement package was suggested.

Create beautifull REST APIs

0.10.0 2017-06-28 02:43 UTC

README

Deprecated

Resty

Librería super sencilla, basada en Slim, para crear servicios Restfull.

Build Status

Latest Stable Version Latest Unstable Version License composer.lock Total Downloads

Versión estable

0.10.0

License

The MIT License (MIT). Ver el archivo LICENSE para más información

Documentación

(pendiente)

Ver archivo doc/README.md

Ejemplos

Devolver un mensaje JSON simple

$path = realpath(__DIR__.'/../');
require $path."/vendor/autoload.php";

// uses
use Resty\Api;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

// configuración
$configFilePath = __DIR__.'/config.php';
$config = include_once $configFilePath;

// Instancia la api
$app = new Api($config);

// Ruta
$app->get(
    '/', 
    function (Request $request, Response $response) {
        $data = ['status' => 'ok'];
        return $response->write($data);
    }
);

$app->run();

Resultado

Como se puede ver, automáticamente devuelve la respuesta en formato json (ver cabeceras)

$ curl -H "Cache-Control: no-cache" -v "http://localhost:5005/"
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5005 (#0)
> GET / HTTP/1.1
> Host: localhost:5005
> User-Agent: curl/7.47.0
> Accept: */*
> Cache-Control: no-cache
> 
< HTTP/1.1 200 OK
< Host: localhost:5005
< Connection: close
< X-Powered-By: PHP/7.0.12
< Content-Type: application/json;charset=utf-8
< Content-Length: 15
< 
{
    "status":"ok"
}
* Closing connection 0

Devolver un mensaje JSON usando Hateoas

$path = realpath(__DIR__.'/../');
require $path."/vendor/autoload.php";

// uses
use Resty\Api;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Mostofreddy\Hateoas\Message;

// configuración
$configFilePath = __DIR__.'/config.php';
$config = include_once $configFilePath;

// Instancia la api
$app = new Api($config);

// Ruta
$app->get(
    '/', 
    function (Request $request, Response $response) {

        $usuario = new Message();
        $usuario->add("Nombre", "Federico")
            ->addLink("self", "http://myapi/user/1");

        $returnMessage = new Message();
        $returnMessage->add("Reporte", "usuarios")
            ->add("usuarios", [$usuario])
            ->addLink("self", "http://myapi/usuarios");

        return $res->ok($returnMessage, 200, JSON_PRETTY_PRINT);
    }
);

$app->run();

Respuesta

$ curl -H "Cache-Control: no-cache" -v "http://localhost:5005"
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5005 (#0)
> GET /saludo HTTP/1.1
> Host: localhost:5005
> User-Agent: curl/7.47.0
> Accept: */*
> Cache-Control: no-cache
> 
< HTTP/1.1 200 OK
< Host: localhost:5005
< Connection: close
< X-Powered-By: PHP/7.0.12
< Content-Type: application/json;charset=utf-8
< Content-Length: 260
< 
{
    "Reporte": "usuarios",
    "usuarios": [
        {
            "Nombre": "Federico",
            "links": {
                "self": "http:\/\/myapi\/user\/1"
            }
        }
    ],
    "links": {
        "self": "http:\/\/myapi\/usuarios"
    }
* Closing connection 0
}

Ejemplo excepción

$path = realpath(__DIR__.'/../');
require $path."/vendor/autoload.php";

// uses
use Resty\Api;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Mostofreddy\Hateoas\Message;

// configuración
$configFilePath = __DIR__.'/config.php';
$config = include_once $configFilePath;

// Instancia la api
$app = new Api($config);

// Ruta
$app->get(
    '/', 
    function (Request $request, Response $response) {
        throw new \Exception("Algo paso");
    }
);

$app->run();

Respuesta

$ curl -H "Cache-Control: no-cache" -v "http://localhost:5005"
* Rebuilt URL to: http://localhost:5005/
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5005 (#0)
> GET / HTTP/1.1
> Host: localhost:5005
> User-Agent: curl/7.47.0
> Accept: */*
> Cache-Control: no-cache
> 
< HTTP/1.1 500 Internal Server Error
< Host: localhost:5005
< Connection: close
< X-Powered-By: PHP/7.0.12
< Content-Type: application/json;charset=utf-8
< Content-Length: 134
< 
{
    "errors":[
        {
            "title":"Resty Application Error",
            "details":[
                {
                    "type":"Exception",
                    "code":0,
                    "message":"Algo paso"
                }
            ],
            "code":0,
            "status":500
        }
    ]
}
* Closing connection 0

Ejemplo ruta no encontrada

$ curl -H "Cache-Control: no-cache" -v "http://localhost:5005/notfound"
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5005 (#0)
> GET /notfound HTTP/1.1
> Host: localhost:5005
> User-Agent: curl/7.47.0
> Accept: */*
> Cache-Control: no-cache
> 
< HTTP/1.1 404 Not Found
< Host: localhost:5005
< Connection: close
< X-Powered-By: PHP/7.0.12
< Content-Type: application/json;charset=utf-8
< Content-Length: 122
< 
{
    "errors":[
        {
            "title":"Page not found",
            "details":"Request => GET:http:\/\/localhost:5005\/notfound",
            "code":0,
            "status":404
        }
    ]
}
* Closing connection 0