REST API – Using Date Type in JAX-RS @PathParam

date formatrest

This is what I'm thinking about doing on a JEE Glassfish server using Jersey.

@GET
@Path("/{name}/{date}")
public String getMessages(@PathParam("name") String name, @PathParam("date") Date date)

I like the idea of being able to tell people consuming this RESTful webservice that "The date here is anything that works with the Date class in Java". That's pretty simple from the standpoint that they can just look at the Date spec, and they'll already have a working model that they can test with.

The problem that I'm worried about is that when I do this, JAX-RS is not very nice when Date() doesn't like what it gets in the constructor. Since Date() throws an error if it can't parse what it's given (like if you pass it the string "today" instead of a real date), the JEE server returns a 404 error.

Is this a good practice? Is there a better way to do this that I'm not thinking of?

Best Answer

Sounds like a bad idea. For one thing, the Date constructor that you'd be relying on has been deprecated since Java 1.1 in favor of DateFormat.parseDate(), precisely because it's unclear how strings should be parsed into dates, as the rules are different for different localities.

My recommendation would be to stick with a specific format, preferably the internationally understood yyyy-MM-dd, and use a DateFormat to parse the date from a string inside your service, which makes it clear how to consume the web service, and allows you to follow whatever the standard convention for returning error messages is for your web services when something goes wrong.