Drupal 8 提供REST服务实例 An Introduction to RESTful Web Services in Drupal 8

  drupal8 的核心模块已经支持REST服务。 这样的话使用drupal 对外提供web service 变的简单了。

 测试一下d8 的webservice :

  extend 中的 依赖模块:全部启用,同时需要一个可视化的资源管理工具,此模块为 RESTUI  下载:  RESTUI

Drupal 8 提供REST服务实例
An Introduction to RESTful Web Services in Drupal 8

第二步,设置用户的访问权限。 people 中的 permission 中设置,此处仅开发了对匿名用户的GET权限

Drupal 8 提供REST服务实例
An Introduction to RESTful Web Services in Drupal 8

在RESTUI 中设置资源格式: configuration ---》rest 中设置

 默认的node 是可用的资源

Drupal 8 提供REST服务实例
An Introduction to RESTful Web Services in Drupal 8

只勾选了 json格式

Drupal 8 提供REST服务实例
An Introduction to RESTful Web Services in Drupal 8

以上准备工作完成。使用Chrome的 Postman rest client 做测试:

POSTman 下载地址:postman   按照说明安装,解压错误请忽略。

最早的版本测试 REST 服务的话  需要添加  header   accept: application/json 之后官方放弃这种方式:参考:Accept header based routing got replaced by a query parameter

采用 url 中 添加参数的方法 指定返回类型: ?_format=hal_json  

 下边仅仅测试 json格式的返回值:

Drupal 8 提供REST服务实例
An Introduction to RESTful Web Services in Drupal 8

 在网页上测试 没有问题:

<!doctype html>
<html>
 <head>
    <meta charset ="utf-8">
    <script type="text/javascript" src="jquery.js"></script>
 </head>
 <body>
 </body>
 
 <script>
    jQuery.ajax({
        url: 'http://localhost:8080/d8/node/3?_format=json',
        method: 'GET',
        dataType:'json',
        success: function (data){
        console.log(data.body[0]['value']);
        console.log(data['body'][0]['value']);
        console.log(data['body'][0].value);
        }
    });
 </script>
</html>

Drupal 8 提供REST服务实例
An Introduction to RESTful Web Services in Drupal 8

console 中打印内容:

Drupal 8 提供REST服务实例
An Introduction to RESTful Web Services in Drupal 8

下边文章及评论具有参考价值: