具有Spring RESTController的端点的REST API层次结构

时间:2018-07-07 17:38:11

标签: java rest spring-boot web

我具有一些REST API的播放器资源URI:

http://localhost:8080/player

http://localhost:8080/player/3 ----> ID为3的播放器资源的URI

我有用于游戏资源的URI:

http://localhost:8080/player/3/games

http://localhost:8080/player/3/games/5 ---> id = 3的玩家(玩此游戏的玩家)的id = 5的游戏资源的URI。

在Spring框架中,我需要两个RestController,一个用于播放器资源,另一个用于游戏资源,但是使用@RequestMapping注释,我这样:

@RestController
@RequestMapping("${spring.data.rest.base-path}" + "/players")
public class PlayerRestResource {

    @RequestMapping( method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public PlayerDto createPlayer(@RequestBody PlayerDTO newPlayerDTO) {
        ...
    }
....
}

但是我不知道如何对像这样的gameRestResource使用RequestMapping注释并获得玩家的ID:

@RestController
@RequestMapping("${spring.data.rest.base-path}" + "/player/idplayer/games")
public class GameRestResource {

    @RequestMapping( method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public GameDto createGame(@RequestBody GameDTO newGameDTO) {
        ...
    }
....
}

1 个答案:

答案 0 :(得分:1)

您必须在方法而非类上添加特定的映射。

为了保持一致,您应该在路径中使用单数或复数名词。例如。玩家与玩家或游戏与游戏。我更喜欢单数名词作为我的休息服务-但这主要是一个主观意见。只要记住您的路径应该只包含名词而不能包含动词(创建,检索,更新等操作)。诸如GET,POST,PUT,DELETE之类的HTTP方法是您的操作,因此您的路径中不需要动词。

您可以通过不同的方法返回资源。我建议您阅读此question

@RestController
@RequestMapping("${spring.data.rest.base-path}" + "/player")
public class PlayerRestResource {

    //This method can be accessed from /player/3
    //Id need to be placed in curly. 3 from url will be passed to the method
    @RequestMapping(path = "/{playerId}", method = RequestMethod.POST)
    //Use @PathVariable to bind the value from to url to the method parameter.
    public ResponseEntity<Player> getPlayer(@PathVariable("playerId") int playerId) {
    }

    //This is just like the above method.
    //This method can be accessed from /player/3/game/5
    @RequestMapping(path = "/{playerId}/game/{gameId}" method = RequestMethod.POST)
    public ResponseEntity<List<Game>> getGame(@PathVariable("playerId) int playerId, @PathVariable("gameId) int gameId) {
    }

}

格式化休息服务的速成课程。

您始终希望在自己的道路上立足。基本变量应该是您的基本实体。

创建新播放器-有效载荷可以在正文中格式化为JSON

POST: example.com/player

获取有关ID为3的玩家的信息。

GET: example.com/player/3

有关ID为3的玩家的更新信息-有效载荷可以在主体中格式化为JSON

PUT: example.com/player/3

删除ID为3的播放器

DELETE: example.com/player/3

获取与ID 3的玩家相关联的ID 5的游戏的信息。请注意,此路径应用于为特定用户更新特定玩家的数据

GET: example.com/player/3/game/5

创建新游戏-正文中的有效载荷可以设置为JSON格式

POST: example.com/game

获取有关ID为5的游戏的信息-此数据未与任何玩家相关联。这只是ID为5的特定游戏的数据。

GET: example.com/player/5

所有以/ player开头的路径都应该进入PlayerController类,而所有以/ game开头的路径都应该在GameController类中。

我建议您阅读以下资源:

https://martinfowler.com/articles/richardsonMaturityModel.html

https://www.restapitutorial.com/

https://spring.io/guides/tutorials/bookmarks/

相关问题