REST GET with Example – RESTful Web Services Tutorial
7 years ago Lalit Bhagtani 0
In REST GET is a method level annotation, this annotation indicates that the following method will respond to the HTTP GET request only. It is used to get a resource identified by requested URI.
Let’s try to understand it with an example.
REST GET method Example 1 :-
In this example, we will hit this URL <base URL>/books with HTTP GET method to get all the books resource.
import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("books") public class GetMethodExample { @GET @Produces(MediaType.TEXT_PLAIN) public Response getAllBooks(){ return Response.status(200) .entity("All Books from 1 to 100").build(); } }
Result :-
Example 2 :-
In this example of REST GET, we will use @PathParam annotation to get the value of the parameter passed in this URL <base URL>/books/{id} with HTTP GET method.
import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("books") public class GetMethodExample { @GET @Produces(MediaType.TEXT_PLAIN) @Path("/{id}") public Response getAllBooks(@PathParam("id") String bookId){ return Response.status(200) .entity("Book id is : " + bookId).build(); } }
Result :-
References :-
That’s all for REST GET with Example. If you liked it, please share your thoughts in comments section and share it with others too.