Drupal 8 REST资源POST方法

时间:2015-12-31 10:21:25

标签: rest drupal-8

我需要帮助在Drupal 8中使用POST方法实现自定义REST API。

我有一个REST资源插件类,里面有一个get()方法。 我可以通过GET方法访问此资源,并且工作正常。

我在同一个类中有一个post()方法,但是无法通过POST方法访问资源,即使在通过“REST UI”模块查看时显示“POST”。

REST UI Settings page

但是当通过POST方法访问时,它显示以下错误。

{"message":"No route found for \u0022POST \/iot\/location\/\u0022: Method Not Allowed (Allow: GET)"}

我正在使用POSTMAN Chrome扩展程序,屏幕截图如下 Testing REST API

我使用以下博客编写REST API,我的代码与此博客文章中显示的代码几乎相同

http://enzolutions.com/articles/2014/12/16/how-to-create-a-rest-resource-in-drupal-8/

先谢谢。

1 个答案:

答案 0 :(得分:0)

确保您已在REST资源中设置uri_paths,包括" https://www.drupal.org/link-relations/create"。

例如,您可能会遇到以下情况:

/**
 * My REST Resource
 *
 * @RestResource(
 *   id = "my_rest_resource",
 *   label = @Translation("My REST Resource"),
 *   uri_paths = {
 *     "canonical" = "/my_rest/resource"
 *   }
 * )
 */

要POST到上述资源,您将使用端点/my_rest_resource。如果您想要POST到/my_rest/resource,请添加链接关系条目:

/**
 * My REST Resource
 *
 * @RestResource(
 *   id = "my_rest_resource",
 *   label = @Translation("My REST Resource"),
 *   uri_paths = {
 *     "canonical" = "/my_rest/resource",
 *     "https://www.drupal.org/link-relations/create" = "/my_rest/resource"
 *   }
 * )
 */

添加https://www.drupal.org/link-relations/create后,您可能需要清除缓存。我发现GET可能与第一个示例一样正常工作,而POST失败并且错误" 405方法不允许"。

Drupal的文档(https://www.drupal.org/docs/8/api/restful-web-services-api/restful-web-services-api-overview)中有关此主题的措辞可能会更加清晰。

相关问题