0

I'm using spring hateoas to create a rest service. I have database entities which I'm exposing through the REST API. To simplify, let's say I have an entity that has three fields as follows.

  • id - a unique identifier
  • service - a service this item belongs to
  • value - a numeric attribute for this item

I am trying to implement the following URL schema:

@RequestMapping(value = "") - return a collection of all items
@RequestMapping(value = "/{id}") - return the specific item with this id @RequestMapping(value = "/{service}") - return a collection of all items with this service

The problem here is the 2nd and 3rd paths are ambiguous and Spring doesn't know which @RequestMapping to match on if I try the URL below for example.

http://localhost/123

How can I deal with this?

conorgriffin
  • 4,282
  • 7
  • 51
  • 88

3 Answers3

3
@RequestMapping(value = "/{id}") 
@RequestMapping(value = "/service/{service}")

You don't have many choices ? But you could also query params with a bit refactoring.

@RequestMapping(value = "/{id}") 
public String myMethod(@RequestParam(value = "service") String service){}
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
1

As you want `/{service} to return a collection with the specified service, a more "correct" approach is probably to add that to your "/" requestmapping as a query parameter.

@RequestMapping(value = "")
public CollectionResource getItems(@RequestParam(value = "service", required = false) String serviceType)

And use something like

http://localhost // return all
http://localhost/123 // return item with ID 123
http://localhost?service=abc // return all items with service abc
Ross Taylor-Turner
  • 3,687
  • 2
  • 24
  • 33
1

It depends on what distinguishes an id from a service. If, for instance, an id is a number and a service a string of characters you can use regular expressions like:

@RequestMapping(value = "/{id:\\d+}") 
@RequestMapping(value = "/{service:[a-zA-Z]+}")
a better oliver
  • 26,330
  • 2
  • 58
  • 66
  • Nice tip but I don't have a guarantee that someone won't use a number as a service name in future so this won't work. – conorgriffin May 26 '14 at 09:59