you can create two resource files, one that receives the parameter and another that does not.
Example:
demo_rest_api.info.yml.
name: Demo REST API
description: Define's a custom REST Resource
package: Custom
type: module
core: 8.x
/src/Plugin/rest/resource/DemoResource.php
<?php
namespace Drupal\demo_rest_api\Plugin\rest\resource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
/**
* Provides a Demo Resource
*
* @RestResource(
* id = "demo_resource",
* label = @Translation("Demo Resource"),
* uri_paths = {
* "canonical" = "/api/item"
* }
* )
*/
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);
}
}
/src/Plugin/rest/resource/DemoResource_item_id.php
<?php
namespace Drupal\demo_rest_api\Plugin\rest\resource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
/**
* Provides a Demo Resource
*
* @RestResource(
* id = "DemoResource_item_id",
* label = @Translation("Demo Resource item id"),
* uri_paths = {
* "canonical" = "/api/item/{id}"
* }
* )
*/
class DemoResource_item_id extends ResourceBase {
/**
* Responds to entity GET requests.
* @return \Drupal\rest\ResourceResponse
*/
public function get($id= null) {
$response = ['message' => 'Hello, this is a rest service and parameter is: '.$id];
return new ResourceResponse($response);
}
}