How to Set Cookie in REST API Response?

Lokesh Gupta

In this Jersey example, we will learn to set cookies into HTTP responses sent by Jersey REST APIs. This example makes use of javax.ws.rs.core.Response for setting cookies into REST responses sent to REST clients.

1. Set Cookie Syntax

To set a cookie in REST API response, get the Response reference and use it’s cookie() method to add the instances of NewCookie class. When sent in a response, NewCookie sets a Set-Cookie response header with the cookie information.

We can add multiple cookies in the same response.

Response.ok().entity(list)
	.cookie(new NewCookie("key1", "value1"))
	.cookie(new NewCookie("key2", "value2"))
	.build();

2. Rest API Example Code

I have written below REST API below for testing purposes.

import com.howtodoinjava.demo.resources.model.Item;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.NewCookie;
import jakarta.ws.rs.core.Response;
import java.util.List;

@Path("items")
public class MyResource {

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response getAllItems() {

    List items = List.of(new Item(1L, "Item1"), new Item(2L, "Item2"));

    return Response.ok().entity(items)
        .cookie(new NewCookie("key1", "value1"))
        .cookie(new NewCookie("key2", "value2"))
        .build();
  }
}

3. Demo

Now let’s call the above REST API in the browser / postman and verify the cookies that have been set into the response.

We can verify the cookies using the Jersey Client API as well:

  @Test
  public void testGetAllItemsResponse() {

    Response response = target.path("items").request().get();

    Assertions.assertEquals(200, response.getStatus());
    Assertions.assertEquals(2, response.getHeaders().get("Set-Cookie").size());
    Assertions.assertEquals("key1=value1;Version=1", response.getHeaders().get("Set-Cookie").get(0));
    Assertions.assertEquals("key2=value2;Version=1", response.getHeaders().get("Set-Cookie").get(1));
  }

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.