Apin Pratap
Apin Pratap

Reputation: 94

Drupal 8 REST resource POST method

I need help to implement a custom REST API using POST method in Drupal 8.

I have a REST resource plugin class, and a get() method in it. I am able to access this resource through GET method and is working fine.

I have a post() method in the same class, but is unable to access the resource through POST method, even though "POST" is displayed when viewing through "REST UI" module.

REST UI Settings page

But when accessing through POST method it displayed following error.

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

I am using POSTMAN Chrome extension and the screenshot is below Testing REST API

I have used following blog to write the REST API and my code is almost same as the code shown in this blog post

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

Thanks in Advance.

Upvotes: 4

Views: 3601

Answers (1)

imclean
imclean

Reputation: 349

Make sure you have set uri_paths in your REST Resource including "https://www.drupal.org/link-relations/create".

For example you may have something like this:

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

To POST to the above resource you would use the endpoint /my_rest_resource. If you're wanting to POST to /my_rest/resource instead then add the link relations entry:

/**
 * 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"
 *   }
 * )
 */

You may need to clear the cache after adding https://www.drupal.org/link-relations/create. I've found that GET may work as expected with the first example while POST fails with the error "405 method not allowed".

The wording on this topic in Drupal's documentation ( https://www.drupal.org/docs/8/api/restful-web-services-api/restful-web-services-api-overview ) could be a little clearer.

Upvotes: 1

Related Questions