Wednesday, 29 August 2012

JAX-RS Annotations (Java API for RESTful Web Services)

1. @GET@POST@PUT@DELETE

  • What: Specifies the HTTP method for a REST endpoint.

  • Why: Required in JAX-RS REST APIs.

  • Where: On resource methods.

  • When to use: When building REST APIs using JAX-RS (like Jersey).

@GET
@Path("/users")
public List<User> getUsers() { ... }

2. @Produces@Consumes

  • What: Specifies the MIME media types produced or consumed.

  • Why: Controls content negotiation.

  • Where: On resource classes or methods.

  • When to use: To define JSON/XML input-output formats.

@POST
@Consumes("application/json")
@Produces("application/json")

3. @Path

  • What: Binds a class or method to a specific URI path.

  • Why: Maps HTTP requests to specific JAX-RS resources.

  • Where: Resource classes and methods.

  • When to use: In JAX-RS-based APIs.

@Path("/api")
public class UserResource { }

4. @PathParam@QueryParam

  • What: Binds URI path/query parameters to method arguments.

  • Why: Enables data extraction from request URL.

  • Where: On method parameters.

  • When to use: In JAX-RS resources.

@GET
@Path("/user/{id}")
public User getUser(@PathParam("id") int id) { }

@GET
@Path("/search")
public List<User> search(@QueryParam("name") String name) { }