Java 8 LocalDate Jackson format

I was never able to get this to work simple using annotations. To get it to work, I created a ContextResolver for ObjectMapper, then I added the JSR310Module (update: now it is JavaTimeModule instead), along with one more caveat, which was the need to set write-date-as-timestamp to false. See more at the documentation for the … Read more

JAX-RS / Jersey how to customize error handling?

There are several approaches to customize the error handling behavior with JAX-RS. Here are three of the easier ways. The first approach is to create an Exception class that extends WebApplicationException. Example: public class NotAuthorizedException extends WebApplicationException { public NotAuthorizedException(String message) { super(Response.status(Response.Status.UNAUTHORIZED) .entity(message).type(MediaType.TEXT_PLAIN).build()); } } And to throw this newly create Exception you simply: … Read more

JAX-RS — How to return JSON and HTTP status code together?

Here’s an example: @GET @Path(“retrieve/{uuid}”) public Response retrieveSomething(@PathParam(“uuid”) String uuid) { if(uuid == null || uuid.trim().length() == 0) { return Response.serverError().entity(“UUID cannot be blank”).build(); } Entity entity = service.getById(uuid); if(entity == null) { return Response.status(Response.Status.NOT_FOUND).entity(“Entity not found for UUID: ” + uuid).build(); } String json = //convert entity to json return Response.ok(json, MediaType.APPLICATION_JSON).build(); } Take … Read more

REST response code for invalid data

400 is the best choice in both cases. If you want to further clarify the error you can either change the Reason Phrase or include a body to explain the error. 412 – Precondition failed is used for conditional requests when using last-modified date and ETags. 403 – Forbidden is used when the server wishes … Read more

When to use @QueryParam vs @PathParam

REST may not be a standard as such, but reading up on general REST documentation and blog posts should give you some guidelines for a good way to structure API URLs. Most rest APIs tend to only have resource names and resource IDs in the path. Such as: /departments/{dept}/employees/{id} Some REST APIs use query strings … Read more

How to implement REST token-based authentication with JAX-RS and Jersey

How token-based authentication works In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization. In a few words, an authentication scheme … Read more