简体   繁体   English

正确的RESTfull Web服务响应

[英]Correct response of RESTfull web service

What should I return (JSON format) after GET, POST, PUT, DELETE requests? GET,POST,PUT,DELETE请求后,我应该返回什么(JSON格式)?

I saw several variants. 我看到了几种变体。 For example: 1) GET: 例如:1)GET:

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET,
        headers = "Accept=application/json")
public Shop getShopById(@PathVariable long id) {
    return mainService.getShopById(id);
}

2) GET: 2)获取:

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET,
        headers = "Accept=application/json")
public ResponseEntity<Shop> getShopById(@PathVariable long id) {
    Shop shop = mainService.getShopById(id);

    if (shop == null) {
        return new ResponseEntity<Shop>(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Shop>(shop, HttpStatus.OK);
}

1) POST: 1)开机自检:

@RequestMapping(value="/users", method = RequestMethod.POST)
public User addShop(@RequestBody User user) {
    mainService.addShop(user);
    return user;enter code here
}

2) POST: 2)开机自检:

@RequestMapping(value="/users", method = RequestMethod.POST)
public User addShop(@RequestBody User user) {
    mainService.addShop(user);

    HttpHeaders headers = new HttpHeaders(); headers.setLocation(ucBuilder.path("/users").buildAndExpand(user.getId()).toUri());
    return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}

So what is the correct way to return the response? 那么返回响应的正确方法是什么? Should it be just an object as User or ResponseEntity ? 它应该只是User或ResponseEntity的对象吗? The same question about PUT and DELETE methods. 关于PUT和DELETE方法的相同问题。

您可能想看看HATEOAS

As far as I know, it depends on what HttpStatus (response code) you want to return. 据我所知,这取决于您要返回的HttpStatus(响应代码)。 I always return ResponseEntity≤?> because it allows to specify HttpStatus, what is important for REST. 我总是返回ResponseEntity≤?>,因为它允许指定HttpStatus,这对REST很重要。

(you also should specify @ResponseBody and produces = MediaType.APPLICATION_JSON_VALUE) (您还应该指定@ResponseBody并产生= MediaType.APPLICATION_JSON_VALUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM