Restful : multiple cases for a same ressource (same api end point ?)

拈花ヽ惹草 提交于 2019-12-11 15:32:11

问题


For example, i have two scenarios for creating a user :

  • Created by administrator, without password. The user will have to choose it on activation page.
  • Created by the user himself, with password. The activation page won't show password inputs because the password already exists.

The thing is it's the same resource, a user. But depending on who (where) the api is called, the expected behaviour is different.

In one case the DTO should contains the password posted by the user, in the other case it shouldn't.

What should i do ?

  • Two api end point with two differents DTO (with and without password) ? But we don't respect the convention that say one end point for creating a given resource
  • Same end point but the DTO received will contain the discriminant to know if we want to handle password or not ? If not, password field must be empty ?
  • Something else ?

I'm not sure how to do this right.

Thank you


回答1:


The best strategy for this situation is passing one attribute in the header of the request. With this information, you can create 2 endpoints using the attribute to direct the request.

Ex:

@PreAuthorize("hasRole('ROLE_USER')")
@PostMapping(headers = "X-YOUR-ORIGIN=user")
public ResponseEntity createUserByUser(){
   ...
}

@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping(headers = "X-YOUR-ORIGIN=admin")
public ResponseEntity createUserByAdmin(){
   ...
}



回答2:


I think the best way would be to make one end point, with an optional parameter. Something like:

@PostMapping public ResponseEntity createUser(@RequestParam(name = "userType") String userType){ //If it's admin, make sure the pwd is set in the dto. Else, it can be null }



来源:https://stackoverflow.com/questions/55208479/restful-multiple-cases-for-a-same-ressource-same-api-end-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!