Deprecated: Array and string offset access syntax with curly braces is deprecated in /home/unareil/www/wiki/inc/init.php on line 557
restler [Wiki Unareil]

Outils pour utilisateurs

Outils du site


restler

Ceci est une ancienne révision du document !



Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in /home/unareil/www/wiki/inc/parser/handler.php on line 1552

Créer votre propre API REST avec [[Restler]]

Ce tutoriel utilise le programme open source Restler 3.0 de Luracast pour créer une API REST.

Commençons par quelque chose de simple : nous allons créer une classe Dis.php qui quand elle sera appelé renverra bonjour suivi du paramètre passer à l'URL.

class Dis {
function bonjour($par='le monde') {
return "Bonjour $par!";
}
}

Maintenant, nous sommes prêt à construire l'index pour le script de notre API. Commençons par télécharger le code Restler et à indiquer qu'il est requis dans notre page d'index.

require_once '../vendor/restler.php';
use Luracast\Restler\Restler;
use Luracast\Restler\Defaults;
Defaults::$smartAutoRouting = false;

La prochaine étape est d'initialiser l'objet Restler et de spécifier que la classe que nous utilisons est exposée à la plateforme Restler par la méthode GET

$r = new Restler();
$r->addAPIClass('Dis');
$r->handle();

C'est fait la plateforme est prête à prendre en compte les requêtes de type REST en utilisant l'URL suivante :

index.php/dis/bonjour/Aurélien Martineau

C'est fait, nous avons réussit à créer une classe et à l'exposer à la méthode de l'URL pour que celle-ci renvoie des informations à l'utilisateur.

Passons maintenant à quelque chose d'utile et plus structuré :

Pour notre exemple, nous allons maintenant créer une API qui est capable de lire et manipuler des données. Nous allons d'abord commencer par créer une simple base de données qui contient une table nommée individu avec le champ id, prenom, nom et email.

Nous allons pouvoir alors rechercher des individus, en ajouter, faire des modification et enfin des suppressions.

Voici la classe en question :

use Luracast\Restler\RestException;
class Individu {
static $FIELDS = array('prenom','nom', 'email');
protected $db;
function __construct(){
$this->db = newMysqlDb('host', 'username', 'password', 'database');
}
function get($id=NULL) {
if($id != NULL){
$this->db->where('person_id', $id);
}
$results = $this->db->get('person');
return $results;
}
}

Il suffit d'exposer maintenant notre class à la plateforme Restler comme nous l'avions fait précédemment pour la classe dis bonjour le monde.

 
require_once '../vendor/restler.php';
use Luracast\Restler\Defaults;
Defaults::$smartAutoRouting = false;
$r = new Restler();
$r->addAPIClass(‘Individu’);
$r->handle();

la suite en anglais ici et très bientôt en français … If you now visit the URL localhost/index.php/person/1, Restler uses the GET method – because that’s the HTTP method you are using – and returns the information in our database that matches an ID of 1. If you don’t specify an ID for a person then all records are returned.

The view of the person database in PhpMyAdmin – notice this very simple database has three fields and the person_id is set to auto_increment

Displaying errors As with all web-based systems providing useful and consistent error codes is extremely important, especially if you are building something that others can integrate into their own systems. Restler allows you to define an error code and output a message to the user. Error codes reflect the HTTP status codes: 1xx - Informational 2xx - Success 3xx - Redirection 4xx - Client Error 5xx - Server Error function get($id = NULL) { if($id != NULL){ $this→db→where('person_id', $id); } $results = $this→db→get('person'); if(empty($results) && $id != NULL){ throw new RestException(400, “This ID doesn't exist”); } return $results; } Now if you visit the localhost/index.php/person/10, you should be presented with the error code and error message:

Restler enables errors to be displayed to the user if you wish; when this is thrown the script doesn’t execute any further actions

Formats You may have noticed that Restler is displaying the data in JSON. This is the default setting, but you can configure your system to return JSON, XML or enable the user to select which one they want to get back. In order to do this, we simply add a new line of code immediately after we call Restler in our index page: $r→setSupportedFormats('XmlFormat','JsonFormat'); You can see that we have specified XML and JSON, the fact that XmlFormat is listed first means that the data is returned in this format by default. If you now visit localhost/index.php/person/1 the data is returned in XML format and you can switch back to JSON by using the following URL localhost/index.php/person.json/1.

If required the returned data can be displayed in XML format: you pass an array to Restler and it does the rest

Voici la source anglophone d'où provient cet article écrit par Richard Askew : https://hungrydevelopers.blogspot.com/2013/08/create-your-own-api-with-restler.html

restler.1559336226.txt.gz · Dernière modification: 2019/05/31 22:57 par unareil