» JAX – RS

JAX-RS stands for:
Java API for RESTful Web Services ,hence it is a http uniformed verb based service.

Some of The main annotations in JAX – RS:
@Path : specifies the relative path for a class or method
@GET/@PUT/@POST/@DELETE/@HEAD: Indicates the http request type on the method but only one can be annotated
@Produces: specifies the MIME media type of the response of a resource
@Consumes: specifies the MIME media type of the request to a resource
@PathParam: is used to extract a parameter from the uri path of a resource
@QueryParam: It is using to extract query parameters from the uri path of a resource

 

Creating an endpoint injecting with CDI the repo into our endpoint
Annotating the code with @Path(“/books”) turns the code into a restful web service.

@Path("/books") 
public class BookEndpoint {


@Inject
private bookRepo BookRepo;

@Get
@Produces(APPLICATION_JSON)
public Response getBooks(){

List<Book> books = bookRepository.findAll();\

if(books.size() == 0)
return Response.status(Response.Status.NO_CONTENT).build(); 

}

return Response.ok(books).build(); 
}


@Get 
@Produces(APPLICATION_JSON)
@Path("/id") 
public Response getBook(@PathParam("id") Long id){ 
Book book = bookRepository.find(id); 
if(book == null) 
return Response.status(Response.Status.NOT_FOUND).build(); 

return Response.ok(book).build();
 } 
 
@Delete 
@Path("/id" : \\d+) 
public Response getBook(@PathParam("id") Long id){ 

  bookRepository.delete(id);
 return Response.noContent().build(); 
}

@Post
@Consumes(APPLICATION_JSON)
 public Response createBook(Book book, @Context UriInfo uriInfo){ 

book = bookRepository.create(book); 
URI createdURI = uriInfogetBaseUriBuilder.path(book.getId()).build();

return Response.created(createdURI).build();

 }