Advertisement
  1. Code
  2. Yii

Programmation avec Yii2: Création d'une API RESTful

Scroll to top
Read Time: 8 min
This post is part of a series called How to Program With Yii2.
How to Program With Yii2: Running Cron Services
Programming With Yii2: Building Community With Voting, Comments, and Sharing

() translation by (you can also view the original English article)

Final product imageFinal product imageFinal product image
What You'll Be Creating

Dans cette Programmation avec la série Yii2, je guide les lecteurs en utilisant Yii2 Framework for PHP. Vous pourriez également être intéressé par mon Introduction au cadre Yii, qui examine les avantages de Yii et comprend un aperçu des nouveautés de Yii 2.x.

Dans le tutoriel d'aujourd'hui, je vais examiner comment créer une API REST dans Yii pour connecter votre application au cloud, aux applications mobiles et à d'autres services. Je vais vous guider dans le guide de démarrage rapide de l'API REST de Yii et fournir un contexte et des exemples de demandes courantes.

Mise en route de Yii REST APIs

Construire des API REST dans Yii est en fait assez simple. Vous pouvez tirer parti du cadre MVC existant, mais vous créez un point d'accès distinct auquel vous souhaitez accéder par différents types de services (pas les visiteurs du site).

Les avantages du cadre Yii REST

Le cadre Yii fournit un support large et une documentation détaillée pour la création d'API. Voici quelques-unes des fonctionnalités intégrées lors de la création d'API:

  • Prototypage rapide avec prise en charge d'API communes pour Active Record. Cela vous permet d'exposer rapidement et facilement les fonctionnalités CRUD des modèles de données via une API.
  • Nécessité du format de réponse (supportant JSON et XML par défaut). Il existe un support intégré pour le retour des données dans les formats de sortie communs.
  • Sérialisation d'objet personnalisable avec support pour les champs de sortie sélectionnables. Il est facile de modifier les données retournées.
  • Mise en forme correcte des données de collecte et des erreurs de validation.
  • Prise en charge d'Hypermedia en tant que moteur d'état d'application (HATEOAS)
  • Routage efficace avec une vérification verbale HTTP appropriée.
  • Prise en charge intégrée des verbes OPTIONS et HEAD.
  • Authentification et autorisation.
  • Mise en cache de données et mise en cache HTTP.
  • Limitation de taux.

Je n'aurai aucune chance de toucher tout cela aujourd'hui.

Mon intérêt pour les API REST

Dans cet épisode, je vais construire une API pour nous permettre de manipuler la table d'objets que j'ai créée dans le service Twixxr à partir de ce tutoriel de l'API Twitter. Mais je prévois également de créer une API pour notre série de tutoriels de démarrage, Meeting Planner. Une API sécurisée sera nécessaire pour créer une application iOS pour le service. L'API permettra la communication entre l'application mobile et le service cloud.

Création du contrôleur REST

Avec le cadre REST de Yii, nous créerons un point d'extrémité pour notre API et organiserons les contrôleurs pour chaque type de ressource.

Les ressources sont essentiellement les modèles de données de notre application. Ceux-ci s'étendent yii\base\Model.

La classe yii\rest\UrlRule fournit un routage pré-établi cartographiant notre modèle de données aux points d'extrémité de l'API CRUD:

Programming Yii2 REST API UrlRule Documentation of CRUD API endpointsProgramming Yii2 REST API UrlRule Documentation of CRUD API endpointsProgramming Yii2 REST API UrlRule Documentation of CRUD API endpoints

Créer un arbre pour agir en tant que point final de l'API

Dans le modèle Yii2 Advanced, il existe un arborescence frontale et arrière-plan, ce qui est extensible. Pour séparer les fonctionnalités de l'API, nous créerons un troisième arbre pour agir uniquement comme point d'extrémité de l'API.

Le développeur Alex Makarov fournit ce guide utile pour créer des arbres supplémentaires que j'ai suivis pour créer mon troisième arbre:

1
$ cp -R backend api
2
$ cp -R environments/dev/backend/ environments/dev/api
3
$ cp -R environments/prod/backend/ environments/prod/api

Ensuite, j'ai utilisé l'éditeur Atom pour trouver une solution globale et remplacer "backend" par "api" dans le nouvel arbre api.

Et j'ai ajouté l'api alias à /common/config/bootstrap.php:

1
<?php
2
Yii::setAlias('@common', dirname(__DIR__));
3
Yii::setAlias('@frontend', dirname(dirname(__DIR__)) . '/frontend');
4
Yii::setAlias('@backend', dirname(dirname(__DIR__)) . '/backend');
5
Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
6
Yii::setAlias('@console', dirname(dirname(__DIR__)) . '/console');
7
Yii::setAlias('@twixxr', dirname(dirname(__DIR__)) . '/twixxr');

Configuration du routage d'URL pour les demandes entrantes

Dans /api/config/main.php, nous devons ajouter la request[] pour analyser l'analyse de configuration JSON et l'UrlRule pour associer les méthodes pour les modèles et leurs points d'extrémité:

1
return [
2
    'id' => 'app-api',
3
    'basePath' => dirname(__DIR__),
4
    'controllerNamespace' => 'api\controllers',
5
    'bootstrap' => ['log'],
6
    'modules' => [],
7
    'components' => [
8
      'request' => [
9
        'parsers' => [
10
          'application/json' => 'yii\web\JsonParser',
11
        ],
12
      ],
13
      'urlManager' => [
14
        'enablePrettyUrl' => true,
15
        'enableStrictParsing' => true,
16
        'showScriptName' => false,
17
        'rules' => [
18
          ['class' => 'yii\rest\UrlRule', 'controller' => 'item'],
19
          ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
20
        ],
21
      ],

C'est tout ce qu'il faut pour permettre une fonctionnalité API riche pour ces modèles.

Exemples avec cURL

Commençons à faire des demandes.

Demander des OPTIONS

Montrez-moi les méthodes API disponibles:

1
curl -i -H "Accept: application/json" 
2
    -X OPTIONS "http://localhost:8888/api/items"

Voici la réponse (GET, POST, HEAD, OPTIONS):

1
HTTP/1.1 200 OK
2
Date: Tue, 25 Oct 2016 20:23:10 GMT
3
Server: Apache/2.2.31 (Unix) mod_wsgi/3.5 Python/2.7.12 PHP/7.0.10 mod_ssl/2.2.31 OpenSSL/1.0.2h DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.24.0
4
X-Powered-By: PHP/7.0.10
5
Allow: GET, POST, HEAD, OPTIONS
6
Content-Length: 0
7
Content-Type: application/json; charset=UTF-8

GET Demandes

Demande: quelle est la quantité de données disponibles?

1
curl -i --head  "http://localhost:8888/api/items"

Réponse: 576 enregistrements sur 29 pages...

1
HTTP/1.1 200 OK
2
Date: Tue, 25 Oct 2016 23:17:37 GMT
3
Server: Apache/2.2.31 (Unix) mod_wsgi/3.5 Python/2.7.12 PHP/7.0.10 mod_ssl/2.2.31 OpenSSL/1.0.2h DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.24.0
4
X-Powered-By: PHP/7.0.10
5
X-Pagination-Total-Count: 576
6
X-Pagination-Page-Count: 29
7
X-Pagination-Current-Page: 1
8
X-Pagination-Per-Page: 20
9
Link: <http://localhost:8888/api/items?page=1>; rel=self, <http://localhost:8888/api/items?page=2>; rel=next, <http://localhost:8888/api/items?page=29>; rel=last
10
Content-Type: application/json; charset=UTF-8

Demande: Montrez-moi fiche 15:

1
curl -i  "http://localhost:8888/api/items/15"

Réponse:

1
HTTP/1.1 200 OK
2
Date: Tue, 25 Oct 2016 23:19:27 GMT
3
Server: Apache/2.2.31 (Unix) mod_wsgi/3.5 Python/2.7.12 PHP/7.0.10 mod_ssl/2.2.31 OpenSSL/1.0.2h DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.24.0
4
X-Powered-By: PHP/7.0.10
5
Content-Length: 203
6
Content-Type: application/json; charset=UTF-8
7
8
{"id":15,"title":"Jeff Reifman","path":"jeffreifman",
9
"detail":"","status":0,"posted_by":1,"image_url":"",
10
"favorites":0,"stat_1":0,"stat_2":0,"stat_3":0,"created_at":1477277956,"updated_at":1477277956}

Demande: Montrez-moi toutes les données à la page 3:

1
curl -i -H "Accept:application/json"
2
    "http://localhost:8888/api/items?page=3"

Réponse:

1
HTTP/1.1 200 OK
2
Date: Tue, 25 Oct 2016 23:30:21 GMT
3
Server: Apache/2.2.31 (Unix) mod_wsgi/3.5 Python/2.7.12 PHP/7.0.10 mod_ssl/2.2.31 OpenSSL/1.0.2h DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.24.0
4
X-Powered-By: PHP/7.0.10
5
X-Pagination-Total-Count: 575
6
X-Pagination-Page-Count: 29
7
X-Pagination-Current-Page: 3
8
X-Pagination-Per-Page: 20
9
Link: <http://localhost:8888/api/items?page=3>; rel=self, <http://localhost:8888/api/items?page=1>; rel=first, <http://localhost:8888/api/items?page=2>; rel=prev, <http://localhost:8888/api/items?page=4>; rel=next, <http://localhost:8888/api/items?page=29>; rel=last
10
Content-Length: 3999
11
Content-Type: application/json; charset=UTF-8
12
13
[{"id":43,"title":"_jannalynn","path":"_jannalynn",
14
"detail":"","status":0,"posted_by":1,"image_url":"",
15
"favorites":0,"stat_1":0,"stat_2":0,"stat_3":0,
16
...
17
...
18
...
19
{"id":99,"title":"alibrown","path":"alibrown","detail":"",
20
"status":0,"posted_by":1,"image_url":"","favorites":0,
21
"stat_1":0,"stat_2":0,"stat_3":0,"created_at":1477277956,
22
"updated_at":1477277956}]

DELETE Demandes

Voici un exemple d'une requête GET suivie d'une requête DELETE puis d'une tentative GET de suivi:

1
$ curl -i -H "Accept: application/json" "http://localhost:8888/api/items/8"
2
HTTP/1.1 200 OK
3
Date: Tue, 25 Oct 2016 23:32:17 GMT
4
Server: Apache/2.2.31 (Unix) mod_wsgi/3.5 Python/2.7.12 PHP/7.0.10 mod_ssl/2.2.31 OpenSSL/1.0.2h DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.24.0
5
X-Powered-By: PHP/7.0.10
6
Content-Length: 186
7
Content-Type: application/json; charset=UTF-8
8
9
{"id":8,"title":"aaker","path":"aaker","detail":"","status":0,"posted_by":1,"image_url":"","favorites":0,"stat_1":0,"stat_2":0,"stat_3":0,"created_at":1477277956,"updated_at":1477277956}
10
11
$ curl -i -H "Accept: application/json" -X DELETE "http://localhost:8888/api/items/8"
12
HTTP/1.1 204 No Content
13
Date: Tue, 25 Oct 2016 23:32:26 GMT
14
Server: Apache/2.2.31 (Unix) mod_wsgi/3.5 Python/2.7.12 PHP/7.0.10 mod_ssl/2.2.31 OpenSSL/1.0.2h DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.24.0
15
X-Powered-By: PHP/7.0.10
16
Content-Length: 0
17
Content-Type: application/json; charset=UTF-8
18
19
$ curl -i -H "Accept: application/json" "http://localhost:8888/api/items/8"
20
HTTP/1.1 404 Not Found
21
Date: Tue, 25 Oct 2016 23:32:28 GMT
22
Server: Apache/2.2.31 (Unix) mod_wsgi/3.5 Python/2.7.12 PHP/7.0.10 mod_ssl/2.2.31 OpenSSL/1.0.2h DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.24.0
23
X-Powered-By: PHP/7.0.10
24
Content-Length: 115
25
Content-Type: application/json; charset=UTF-8
26
27
{"name":"Not Found","message":"Object not found: 8","code":0,"status":404,"type":"yii\\web\\NotFoundHttpException"}

Les demandes d'enregistrement supprimé renvoient une erreur 404.

POST Demandes

Pour mes demandes de publication, je suis passé à l'application Chrome Postman:

Programming With Yii2 Chrome Directory Postman Extension Landing PageProgramming With Yii2 Chrome Directory Postman Extension Landing PageProgramming With Yii2 Chrome Directory Postman Extension Landing Page

S'inscrire pour Postman était facile:

Programming With Yii2 Postmand Sign UpProgramming With Yii2 Postmand Sign UpProgramming With Yii2 Postmand Sign Up

Et puis j'ai pu envoyer des requêtes à mon API localhost dans une interface graphique plus amicale:

Programming With Yii2 POST Request Shown in Postman UXProgramming With Yii2 POST Request Shown in Postman UXProgramming With Yii2 POST Request Shown in Postman UX

Ensuite, j'ai récupéré les données via curl, record 577:

1
$ curl -i -H "Accept: application/json" "http://localhost:8888/api/items/577"
2
HTTP/1.1 200 OK
3
Date: Tue, 25 Oct 2016 23:40:44 GMT
4
Server: Apache/2.2.31 (Unix) mod_wsgi/3.5 Python/2.7.12 PHP/7.0.10 mod_ssl/2.2.31 OpenSSL/1.0.2h DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.24.0
5
X-Powered-By: PHP/7.0.10
6
Content-Length: 219
7
Content-Type: application/json; charset=UTF-8
8
9
{"id":577,"title":"Jeff Reifman","path":"reifman",
10
"detail":"A programmer on earth.","status":0,
11
"posted_by":1,"image_url":"","favorites":0,
12
"stat_1":0,"stat_2":0,"stat_3":0,"created_at":1477436477,
13
"updated_at":1477436477}

Postman s'est avéré essentiel pour compléter mes tests car la ligne de commande n'était pas facile à configurer pour les soumissions POST.

Regarder vers l'avant

En plus de son résumé REST quickstart, la documentation Yii 2.0 fournit des détails sur un ensemble d'autres aspects de la création de l'API:

J'espère avoir la chance d'en explorer davantage dans les épisodes futurs. Mais certainement, l'une des prochaines étapes est de créer une API pour Meeting Planner dans la série de démarrage.

En conclusion, la construction d'une API REST de base avec le cadre Yii MVC est assez simple. L'équipe de Yii a fait un excellent travail en normalisant les fonctionnalités pour une exigence très importante, les API REST. J'espère que vous avez apprécié apprendre à leur sujet.

Si vous avez des questions ou des suggestions, veuillez les publier dans les commentaires. Si vous souhaitez suivre mes futurs tutoriels Envato Tuts+ et d'autres séries, visitez la page de mon instructeur ou suivez @reifman. Vérifiez définitivement ma série de démarrage et Meeting Planner.

Liens connexes

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.