I had a custom REST API working with Drupal 8 perfectly. After upgrading to Drupal 9.2.X, the Patch and Post methods of this custom REST API stopped working. Now they throw the following exception.
RuntimeException: Callable "Drupal\my_module\Plugin\rest\resource\UpdateBoxes::patch" requires a value for the "$payload" argument. in Drupal\Component\Utility\ArgumentsResolver->handleUnresolvedArgument() (line 143 of /var/www/docroot/core/lib/Drupal/Component/Utility/ArgumentsResolver.php).
The code I am using is the following one.
namespace Drupal\my_module\Plugin\rest\resource;
use Drupal\rest\ModifiedResourceResponse;
/**
* Provides a resource to get view modes by entity and bundle.
*
* @RestResource(
* id = "update_boxes",
* label = @Translation("Update boxes"),
* uri_paths = {
* "canonical" = "/api/container/{container_id}/{type}/{product_id}/boxes"
* }
* )
*/
class UpdateBoxes extends ResourceBase {
/**
* A current user instance.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
protected $boxesHandler;
protected $event_dispacher;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->currentUser = $container->get('current_user');
$instance->boxesHandler = $container->get('boxes.handler');
$instance->event_dispacher = $container->get('event_dispatcher');
return $instance;
}
/**
* Responds to PATCH requests.
*
* @param $container_id
* @param $type
* @param $product_id
* @param $payload
* @return \Drupal\rest\ModifiedResourceResponse
* The HTTP response object.
*/
public function patch($container_id = null, $type = null, $product_id = null, $payload) {
//My code here.
}
}
In patch()
I could read $payload
and see the array sent in the request, but after upgrading the site, $payload
is NULL
.
The solution I found was changing the last argument of patch()
and extract the payload from the $request
object.
public function patch($container_id = null, $type = null, $product_id = null, Request $request) {
// …
$payload = json_decode($request->getContent(), TRUE);
}
I couldn't find any documentation about this change; I am not sure it was a good practice or the better implementation to get the payload working.