【问题标题】:Drupal 8 REST resource POST methodDrupal 8 REST 资源 POST 方法
【发布时间】:2015-12-31 10:21:24
【问题描述】:

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

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

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

但是通过 POST 方法访问时显示如下错误。

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

我正在使用 POSTMAN Chrome 扩展程序,截图如下

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

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

提前致谢。

【问题讨论】:

  • 我也在努力创建自定义 POST 端点。不幸的是,似乎没有关于创建自定义 POST 端点的代码或教程,一切都集中在现有的核心实体/{entity_type}/{entity}。我认为问题在于不理解 @RestResource 注释中的 'serialization_class' 和 'deriver' 键。希望搞清楚后能在这里给出答案……
  • 你清除缓存了吗?谢谢。
  • 您是否关注过来自drupal.org/docs/8/api/restful-web-services-api/… 的文档?另外,您使用的是什么版本的 Drupal 8.x(8.1.x、8.2.x)?也许这是 rest_ui 模块的错误。您是否尝试过在没有 rest_ui 帮助的情况下自己创建 yml 文件?

标签: rest drupal-8


【解决方案1】:

确保您在 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"
 *   }
 * )
 */

要发布到上述资源,您将使用端点/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) 中有关此主题的措辞可能会更清晰一些。

【讨论】:

    猜你喜欢
    • 2020-08-26
    • 2018-05-18
    • 2017-02-19
    • 1970-01-01
    • 2015-11-02
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    相关资源
    最近更新 更多