Este es un PHP REST-API que utiliza la autenticación HTTP básica. Dado que la autenticación HTTP básica está codificada pero no está encriptada, se recomienda usar una conexión segura (HTTPS) y una contraseña segura.
Si usa esta API para manejar datos confidenciales, lo hace bajo su propio riesgo.
Configure un servidor MySQL y ejecute example_database.sql . Ingrese los parámetros MySQL relacionados en settings.php .
$ php -S localhost:2400 -t public
La autenticación está habilitada de forma predeterminada. Puede deshabilitarlo en settings.php .
Las siguientes credenciales están actualmente codificadas en el middleware lib/Authentication . Depende de usted implementar una lógica adecuada.
$ username = " rest " ;
$ password = " test " ; Crea servicios en el directorio de services y la carpeta de versión específica. Un servicio siempre hereda del servicio web de clase abstracta. Aquí hay una plantilla básica que puede usar para comenzar rápidamente:
use RESTapi Sources Request ;
use RESTapi Sources Response ;
use RESTapi Sources WebService ;
use RESTapi Library Database ;
class YourService extends WebService {
private Database | null $ db ;
public function __construct ()
{
$ this -> db = Database:: getInstance ();
}
public function get ( Request $ request , Response $ response ): void
{
// Your logic here ...
$ affectedRows = 12 ;
$ response -> write ( " JSON " ); // Add a JSON object
$ response -> addHeader ( " X-Data-Count " , $ affectedRows );
$ response -> setStatus ( 200 );
}
public function post ( Request $ request , Response $ response ): void
{
// Your logic here ...
$ affectedRows = 12 ;
$ response -> write ( " JSON " ); // Add a JSON object
$ response -> addHeader ( " X-Insert-Count " , $ affectedRows );
$ response -> setStatus ( 201 );
}
public function put ( Request $ request , Response $ response ): void
{
// Your logic here ...
$ affectedRows = 1 ;
$ response -> write ( " JSON " ); // Add a JSON object
$ response -> addHeader ( " X-Update-Count " , $ affectedRows );
$ response -> setStatus ( 204 );
}
public function delete ( Request $ request , Response $ response ): void
{
// Your logic here ...
$ affectedRows = 1 ;
$ response -> write ( " JSON " ); // Add a JSON object
$ response -> addHeader ( " X-Delete-Count " , $ affectedRows );
$ response -> setStatus ( 205 );
}
}Trabajando con la base de datos:
Consulte el servicioUserspara aprender y comprender cómo crear consultas para realizar operaciones CRUD.
Uso: GET domain.tld/[version]/[service]
$ ch = curl_init ( " http://localhost:2400/v1/Users/ " );
curl_setopt ( $ ch , CURLOPT_HTTPAUTH , CURLAUTH_BASIC );
curl_setopt ( $ ch , CURLOPT_USERPWD , " $ username : $ password " );
curl_setopt ( $ ch , CURLOPT_HEADER , true );
if (! $ output = curl_exec ( $ ch )) {
trigger_error ( curl_error ( $ ch ));
}
curl_close ( $ ch ); Uso: GET domain.tld/[version]/[service]/[id]
$ ch = curl_init ( " http://localhost:2400/v1/Users/3 " );
curl_setopt ( $ ch , CURLOPT_HTTPAUTH , CURLAUTH_BASIC );
curl_setopt ( $ ch , CURLOPT_USERPWD , " $ username : $ password " );
curl_setopt ( $ ch , CURLOPT_HEADER , true );
if (! $ output = curl_exec ( $ ch )) {
trigger_error ( curl_error ( $ ch ));
}
curl_close ( $ ch ); Uso: POST domain.tld/[version]/[service]
$ body = [
" name " => " Greta Garbo " ,
" age " => " 93 " ,
" city " => " Hollywood " ,
" country " => " California "
];
$ ch = curl_init ( " http://localhost:2400/v1/Users " );
curl_setopt ( $ ch , CURLOPT_POST , true );
curl_setopt ( $ ch , CURLOPT_POSTFIELDS , http_build_query ( $ body ));
curl_setopt ( $ ch , CURLOPT_HTTPAUTH , CURLAUTH_BASIC );
curl_setopt ( $ ch , CURLOPT_USERPWD , " $ username : $ password " );
curl_setopt ( $ ch , CURLOPT_HEADER , true );
if (! $ output = curl_exec ( $ ch )) {
trigger_error ( curl_error ( $ ch ));
}
curl_close ( $ ch ); Uso: PUT domain.tld/[version]/[service]/[id]
$ body = [
" name " => " John Rambo " ,
" age " => " 42 " ,
" city " => " Seattle " ,
" country " => " Washington "
];
$ ch = curl_init ( " http://localhost:2400/v1/Users/4 " );
curl_setopt ( $ ch , CURLOPT_CUSTOMREQUEST , " PUT " );
curl_setopt ( $ ch , CURLOPT_POSTFIELDS , http_build_query ( $ body ));
curl_setopt ( $ ch , CURLOPT_HTTPAUTH , CURLAUTH_BASIC );
curl_setopt ( $ ch , CURLOPT_USERPWD , " $ username : $ password " );
curl_setopt ( $ ch , CURLOPT_HEADER , true );
if (! $ output = curl_exec ( $ ch )) {
trigger_error ( curl_error ( $ ch ));
}
curl_close ( $ ch ); Uso: DELETE domain.tld/[version]/[service]/[id]
$ ch = curl_init ( " http://localhost:2400/v1/Users/1 " );
curl_setopt ( $ ch , CURLOPT_CUSTOMREQUEST , " DELETE " );
curl_setopt ( $ ch , CURLOPT_HTTPAUTH , CURLAUTH_BASIC );
curl_setopt ( $ ch , CURLOPT_USERPWD , " $ username : $ password " );
curl_setopt ( $ ch , CURLOPT_HEADER , true );
if (! $ output = curl_exec ( $ ch )) {
trigger_error ( curl_error ( $ ch ));
}
curl_close ( $ ch ); Un servicio hereda cuatro funciones get , post , put y delete de la clase de servicio web abstracto de forma predeterminada. Esos son perfectos para realizar acciones CRUD en una base de datos. Pero, ¿qué pasa si necesita un servicio que debería hacer algunas tareas especiales? En tal caso, puede usar el PATCH del método de solicitud HTTP y proporcionar el nombre de la acción en el URI.
A continuación se muestra un ejemplo de un servicio de caluculación que multiplica dos números:
Uso: PATCH domain.tld/[version]/[service]/[action]
$ ch = curl_init ( " http://localhost:2400/v1/Calculator/multiply " );
$ body = [
" a " => 12 ,
" b " => 2.5
];
$ ch = curl_init ( $ url );
curl_setopt ( $ ch , CURLOPT_CUSTOMREQUEST , " PATCH " );
curl_setopt ( $ ch , CURLOPT_POSTFIELDS , http_build_query ( $ body ));
curl_setopt ( $ ch , CURLOPT_HTTPAUTH , CURLAUTH_BASIC );
curl_setopt ( $ ch , CURLOPT_USERPWD , " $ username : $ password " );
curl_setopt ( $ ch , CURLOPT_HEADER , true );
if (! $ output = curl_exec ( $ ch )) {
trigger_error ( curl_error ( $ ch ));
}
curl_close ( $ ch );La API responde con los siguientes códigos de estado. Puedes cambiar esto a tu gusto:
Sobre el éxito:
De lo contrario:
A continuación se muestra un patrón de ejemplo que puede usar para construir su propio middleware. Puede crear su propio middleware creando una clase en la carpeta lib que implementa la interfaz Imiddleware :
class YourMiddleware implements IMiddleware {
public function handle ( Request $ request , Response $ response ): void {}
}Para inyectar el middleware en otro middleware, use el constructor de ese middleware:
class YourMiddleware implements IMiddleware {
public function __construct ( private IMiddleware $ anotherMiddleware ) {}
public function handle ( Request $ request , Response $ response ): void
{
// 1. Add your logic ...
// 2. Handle Middleware ...
$ this -> anotherMiddleware -> handle ( $ request , $ response );
// 3. Do something afterwards ...
}
}
$ anotherMiddleware = new AnotherMiddleware ();
$ yourMiddleware = new YourMiddleware ( $ anotherMiddleware );
$ yourMiddleware -> handle ( $ request , $ response );Martin Wolf
MIT