{
"name": "Cyril Lacôte",
"company": "Ninja Squad",
"email": "cyril@ninja-squad.com",
"twitter": "@clacote",
"associations" : ["LyonJUG", "Mix-IT"]
}
http://server.com/users/clacote
GET
POST
PUT
DELETE
getAllUsers
GET /users
getUserById(id)
GET /users/{id}
createUser
POST /users
deleteUser(id)
DELETE /users/{id}
updateUser
PUT /users/{id}
searchUser(criteria)
GET /users/search?name=Lac*&age=34
{
"code": "14",
"developerMessage": "this user has not enough credentials to access admin repository",
"more": "http://mywebsite.com/api/errors/14",
"userMessage": "You can't access this repository",
}
@Controller
@RequestMapping("/spectacle")
public class SpectacleController {
@Autowired
private SpectacleService spectacleService;
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public ModelAndView view(@PathVariable("id") Long id) {
Spectacle spectacle = spectacleService.findById(id);
ModelAndView result = new ModelAndView("spectacle");
result.addObject("spectacle", spectacle);
return result;
}
}
ACCEPT_TYPE
header (if we're nice)CLASSPATH
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(writer, javaObject);
@ResponseBody
on return typeaccept "application/json"
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public @ResponseBody Spectacle view(@PathVariable("id") Long id) {
Spectacle spectacle = spectacleService.findById(id);
return spectacle;
}
Avoid cyclic references!
Lot of ways (check documentation).
Easiest: annotate your model classes.
@JsonIgnore
to ignore attribute@JsonProperty("otherName")
to customize name
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);
@RequestBody
on action method parametercontent-type "application/json"
@RequestMapping(value = "/", method = RequestMethod.POST)
public void Spectacle create(@RequestBody Spectacle spectacle) {
spectacleService.createSpectacle(spectacle);
}
@ExceptionHandler
(in same controller class)
@ExceptionHandler(InvalidRequestException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody String whenInvalidRequest() {
return "invalid data";
}
GET /api/spectacles/ : liste des spectacles
GET /api/spectacles/{id} : détail du spectacle d'identifiant {id}
POST /api/spectacles/ : créer un nouveau spectacle avec gestion d'erreurs (paramètre manquant -> erreur HTTP 400)