2

How should I approach parsing URI parameters in a REST API. For example:

http://api.example.com/item/ [{{ItemID}} [/{{Property}}]]

The following requests should all be valid:

http://api.example.com/item
http://api.example.com/item/
http://api.example.com/item/1
http://api.example.com/item/1/
http://api.example.com/item/1/description
http://api.example.com/item/1/description/

I need to be able to get the ItemID and Property values, if they exist.

I attempted to use Apache Commons StringUtils and the substringBefore/substringAfter, but things soon got confusing. Is there a library for such a task, or another way I overlooked?

vikarjramun
  • 1,042
  • 12
  • 30

2 Answers2

1

If you are using JAX-RS, you can do something like

@GET
@Path("/{param1}/{param2}")
@Produces("text/plain")

public String get(@PathParam("param1") int param1, @PathParam("param2") int param2) {

    logger.debug("\n param1 = " + param1 + " .. param2 = " + param2);
}
Jagdeep
  • 61
  • 6
0

I definitely appreciate @Jagdeep's answer, but since I am not using JAX-RS, I couldn't use it. After doing some research, it was clear that there weren't any libraries to do this, so I decided to create my own. It is very crude, and has no documentation as of now. However, I will update this soon. You are welcome to submit a pull request to me, with improvements.

https://github.com/ArjMart/UrlParser

Usage:

UrlParser parser = new Parser();
parser.setTemplate("/item/{INT:itemID}/{STRING:itemAttribute}");
UrlParametersMap upm = parser.parse(request.getURI());
boolean attributeExists = upm.parameterExists("itemAttribute");
String attribute = null;
if(attributeExists){
  attribute = upm.getString("itemAttribute");
}

Disclaimer: I am (obviously) affiliated with UrlParser as I am its sole creator and contributor.

vikarjramun
  • 1,042
  • 12
  • 30