I have a project based on spring-data-rest and also it has some custom endpoints.
For sending POST data I'm using json like
{
"action": "REMOVE",
"customer": "http://localhost:8080/api/rest/customers/7"
}
That is fine for spring-data-rest, but does not work with a custom controller.
for example:
public class Action {
public ActionType action;
public Customer customer;
}
@RestController
public class ActionController(){
@Autowired
private ActionService actionService;
@RestController
public class ActionController {
@Autowired
private ActionService actionService;
@RequestMapping(value = "/customer/action", method = RequestMethod.POST)
public ResponseEntity<ActionResult> doAction(@RequestBody Action action){
ActionType actionType = action.action;
Customer customer = action.customer;//<------There is a problem
ActionResult result = actionService.doCustomerAction(actionType, customer);
return ResponseEntity.ok(result);
}
}
When I call
curl -v -X POST -H "Content-Type: application/json" -d '{"action": "REMOVE","customer": "http://localhost:8080/api/rest/customers/7"}' http://localhost:8080/customer/action
I have an answer
{
"timestamp" : "2016-05-12T11:55:41.237+0000",
"status" : 400,
"error" : "Bad Request",
"exception" : "org.springframework.http.converter.HttpMessageNotReadableException",
"message" : "Could not read document: Can not instantiate value of type [simple type, class model.user.Customer] from String value ('http://localhost:8080/api/rest/customers/7'); no single-String constructor/factory method\n at [Source: java.io.PushbackInputStream@73af10c6; line: 1, column: 33] (through reference chain: api.controller.Action[\"customer\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class logic.model.user.Customer] from String value ('http://localhost:8080/api/rest/customers/7'); no single-String constructor/factory method\n at [Source: java.io.PushbackInputStream@73af10c6; line: 1, column: 33] (through reference chain: api.controller.Action[\"customer\"])",
"path" : "/customer/action"
* Closing connection 0
}
bacause case spring can not convert a URI to a Customer entity.
Is there any way to use spring-data-rest mechanism for resolving entities by their URIs?
I have only one idea - to use custom JsonDeserializer with parsing URI for extracting entityId and making a request to a repository. But this strategy does not help me if I have URI like "http://localhost:8080/api/rest/customers/8/product" in that case I do not have product.Id value.
http://localhost:8080/api/rest/customers/8/product
is not a URI. Instead of trying to solve this particular problem I strongly recommend to redesign your API. – Quirkhttp://localhost:8080/api/rest/customers/8/product
, because it's not a URI. You never will use that as a reference to a product. – Quirk