DEV Community

Cover image for How to return a response with OK HTTP Status Code with Jax-Rs
Adrian Matei for Codever

Posted on β€’ Edited on β€’ Originally published at codever.dev

5 1

How to return a response with OK HTTP Status Code with Jax-Rs

Use the ok() method of the javax.ws.rs.core.Reponse class to create a ReponseBuilder with a status of 200 (OK),
or the ok(Object entity) to return OK with data

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("comparison")
@Stateless
@Tag(name = "Comparison")
public class ComparisonRestResource {

  @Inject private ComparisonService comparisonService;

  @HEAD
  @Operation(
      summary = "Ping HEAD",
      description = "Check availability of the resource. ")
  @ApiResponses(@ApiResponse(responseCode = "200", description = "Service is reachable via HTTP"))
  public Response head() {
    return Response.ok().build();
  }

  @GET
  @Produces(MediaType.TEXT_PLAIN)
  @Operation(
      summary = "Ping GET",
      description = "Check availability of the example resource. ")
  @ApiResponses(@ApiResponse(responseCode = "200", description = "Service is reachable via HTTP"))
  public Response ping() {
    return Response.ok("pong").build();
  }
}
Enter fullscreen mode Exit fullscreen mode

Note that the ok() methods shown before are just shortcuts for

return Response
        .status(Response.Status.OK)
        .build()
Enter fullscreen mode Exit fullscreen mode

and

return Response
        .status(Response.Status.OK)
        .entity("pong")
        .build()
Enter fullscreen mode Exit fullscreen mode

respectively.


Shared with ❀️ from Codever. Use πŸ‘‰ copy to mine functionality to add it to your personal snippets collection.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay