1

I am working on web services in drupal. I have created a sample module for get method to expose the data using web services. I have not found any sample code for the patch method. code for get method:

namespace Drupal\demo_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

class DemoResource extends ResourceBase {

}
/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "demo_resource",
 *   label = @Translation("Demo Resource"),
 *   uri_paths = {
 *     "canonical" = "/demo_rest_api/demo_resource"
 *   }
 * )
 */
class DemoResource extends ResourceBase {

}
/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "demo_resource",
 *   label = @Translation("Demo Resource"),
 *   uri_paths = {
 *     "canonical" = "/demo_rest_api/demo_resource"
 *   }
 * )
 */
class DemoResource extends ResourceBase {

  /**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function get() {
    $response = ['message' => 'Hello, this is a rest service'];
    return new ResourceResponse($response);
  }
}

I am novice to drupal. I did not find any example for patch method. Can any one usher me or provide a sample code for patch method.

0

It's actually quite simple. You only have to do like this:

public function patch() {
  // Write your code in here.
}

The patch function uses the canonical link just like get.

 * uri_paths = {
 *   "canonical" = "/path-to-endpoint", // Used for GET, PATCH and DELETE.
 *   "create" = "/path-to-endpoint/post" // Used for POST.
 * }

To get the request object, I think that you can use $request as first argument like this:

use Symfony\Component\HttpFoundation\Request;

public function patch(Request $request) {
  // Write your code in here.
}
  • I have tried creating patch function, but I am not sure how to create url for that function and call it. Can u also please show to read data from the body in the request. – user95006 Aug 21 at 11:58
  • I have updated my answer, hope it makes sense. – Jdrupal Aug 21 at 12:14
  • Thanks a lot @Jdrupal – user95006 Aug 21 at 12:18
  • Cool, if the answer helped you, please accept it, thanks. – Jdrupal Aug 21 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.