DEV Community

Cover image for How To return CREATED HTTP Status Code in Jax-Rs
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

3 2

How To return CREATED HTTP Status Code in Jax-Rs

Use created(URI location) of the javax.ws.rs.core.Response class. Usually when you return the 201 HTTP Status Code, you should return a location header with the location where the new REST resource is available.

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

@Path("messages")
@Stateless
@Tag(name = "Message")
public class MessageRestResource {

  @Inject private MessageService messageService;

  @POST
  @Consumes(MediaType.TEXT_PLAIN)
  @Operation(summary = "Create message")
  @ApiResponses({
    @ApiResponse(
        responseCode = "201",
        description = "Message successfully created."),
    @ApiResponse(responseCode = "403", description = "Forbidden")
  })
  public Response createMessage(
      @Parameter(description = "Message") String message, @Context UriInfo uriInfo)
      throws JAXBException {
    Message created = messageService.createMessage(message);
    UriBuilder builder = uriInfo.getAbsolutePathBuilder();
    builder.path(created.getUuid().toString());
    return Response.created(builder.build()).build();
  }
Enter fullscreen mode Exit fullscreen mode

In the snippet the UriBuilder method builder.path(created.getUuid().toString()) appends the identifier of the newly created message (uuid) to the absolute path of the request, which was obtained from the uriInfo


Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.

Billboard image

Monitor more than uptime.

With Checkly, you can use Playwright tests and Javascript to monitor end-to-end scenarios in your NextJS, Astro, Remix, or other application.

Get started now!

Top comments (0)

Bump.sh

Hate writing docs? Hate undocumented APIs even more?

Bump.sh generates an always up-to-date API reference site for REST and Event-Driven Architectures.

Plug it in your CI. It fetches your OpenAPI and AsyncAPI (GraphQL pending) spec files, and even generates a diff. Gather all of your API docs in a single source of truth.

Try it for free

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay