I'm attempting to create a custom rest resource, and have followed very many examples but I can't seem to get it to work. Every time I test it using https://www.hurl.it/ I just get a 301 error.
I'm using http://example.com/myrest_test/1?_format=json as the url as a GET request.
My format is as follows. I have a custom module called rest_test
Inside /rest_test/src/Plugin/rest/resource/MyRestTest.php I have
<?php
namespace Drupal\rest_test\Plugin\rest\resource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
/**
* Provides a resource for accepting rest calls
*
* @RestResource(
* id = "myrest_test",
* label = @Translation("My Rest Test"),
* uri_paths = {
* "canonical" = "/myrest_test/{id}"
* }
* )
*/
class MyRestTest extends ResourceBase {
/**
* Responds to GET requests.
*
*
* @param int $id
* The ID.
*
* @return \Drupal\rest\ResourceResponse
* The response.
*/
public function get($id = null) {
$response = ['message' => 'Hey this worked and this is the id'.$id];
return new ResourceResponse($response);
}
}
and inside a form.js file I have
(function($) {
$(function() {
console.log('form.js executed successfully');
jQuery.ajax({
url: "/myrest_test/5",
}).done(function(msg){
console.log(msg);
});
})
})(jQuery);
I receive the 'form.js executed successfully' message so I'm certain the javascript is running, but msg is empty. I've tried with the entire url instead of just the relative one as well. I've also made sure I'm clearing the cache But I can't seem to get any proper response. Is there something I'm missing? Why doesn't my rest resource response to my ajax calls?
UPDATE: Looking in the error logs it looks like I'm getting page not found errors for that rest call
UPDATE 2: When I visit directly in my browser I receive /myrest_test/{id}
{"message":"No route found for \u0022GET /myrest_test//234\u0022"}
UPDATE 3: After narrowing down the issue to it being a routing problem I found a similar question here No route found for custom REST resource however when I add
* uri_paths = {
* "canonical" = "/myrest_test/{id}",
* "https://www.drupal.org/link-relations/create" = "/myrest_test"
* }
I still encounter the same error