REST endpoints
A REST endpoint is an address a client sends an HTTP request to, plus the code that answers it. In Quarkus, endpoints live in resource classes with annotations from the Jakarta REST standard. The implementation comes from the Quarkus REST extension (quarkus-rest), which is already in the project together with rest-jackson.
The first blog resource
Delete the generated GreetingResource.java and both tests, GreetingResourceTest.java and GreetingResourceIT.java — we no longer need them. Create a resource file for posts:
// src/main/java/com/example/blog/PostResource.java
package com.example.blog;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("/posts")
public class PostResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String list() {
return "The list of posts will be here";
}
}@Path("/posts") sets the address, @GET the HTTP method and @Produces the response type. If dev mode is running, the class works as soon as you save it:
curl http://localhost:8080/postsThe terminal prints The list of posts will be here.
A path in two parts
@Path can also be put on a method. The address is then the class path plus the method path:
// src/main/java/com/example/blog/PostResource.java
@GET
@Path("/latest")
@Produces(MediaType.TEXT_PLAIN)
public String latest() {
return "The latest post";
}This method answers GET /posts/latest.
HTTP methods
| Annotation | Usually used to |
|---|---|
@GET | Read data |
@POST | Create a record |
@PUT | Replace a whole record |
@PATCH | Change part of a record |
@DELETE | Delete a record |
One path can serve several methods: GET /posts returns the list and POST /posts creates a post.
The response type
@Produces tells which format a method returns, and @Consumes which format it accepts. Common values are MediaType.TEXT_PLAIN and MediaType.APPLICATION_JSON. When a method returns an object rather than a string, Quarkus REST picks JSON by itself, so in the next lessons you will rarely need @Produces.
One object for all requests
In Quarkus REST a resource class is created once by default and serves all requests (the @Singleton scope). So do not keep the data of a particular request in the resource's fields — use method parameters for that.
Common mistake
If you call an existing address with a method the resource does not have, Quarkus answers 405:
curl -i -X PUT http://localhost:8080/postsHTTP/1.1 405 Method Not Allowed
content-length: 0
This is not a server error: the address was found, but there is no handler for PUT. Check the method annotation and the -X flag in curl. If the address does not exist at all, the answer is 404 Not Found.