Implementing READ operation

In this step, we'll implement two methods at once. One is for retrieving a single post and another for multiple blog posts. By completing this step, you'll learn to map your service with the HTTP GET (@Get) method, use parameter injection (@Param), set default parameter value (@Default), and return a JSON object (@ProducesJson) as a response.

What you need

You need to have the following files obtained from previous steps. You can always download the full version, instead of creating one yourself.

  • Main.java
  • BlogPost.java
  • BlogService.java
  • BlogServiceTest.java

1. Map HTTP method

Let's start mapping the HTTP GET method with our service method:

Map the HTTP GET method for retrieving a single post:

  1. Declare a service method getBlogPost() in the class BlogService.

  2. Map this service method with the HTTP GET method by adding the @Get annotation as follows.

  3. Bind the endpoint /blogs to the method.

    BlogService.java
    import com.linecorp.armeria.server.annotation.Get;
    
    public final class BlogService {
      ...
    
      @Get("/blogs")
      public void getBlogPost(int id) {
        // Retrieve a single post
      }
    }

2. Handle parameters

Take in information through path and query parameters for retrieving blog posts. For retrieving a single post, we'll take a blog post ID as the path parameter. For multiple posts, we'll take the sorting order as a query parameter.

Let's handle parameters for retrieving a single post:

  1. To take in a path parameter, add /:id to the @Get annotation's parameter as in line 6.
  2. Inject the path parameter to the service method, annotate the parameter with @Param as in line 7.
BlogService.java
1import com.linecorp.armeria.server.annotation.Param;
2
3public final class BlogService {
4 ...
5
6 @Get("/blogs/:id")
7 public void getBlogPost(@Param int id) {
8   // Retrieve a single post
9 }
10}

3. Implement service code

In this step, write the code required for service itself.

To retrieve a single blog post information, copy the following code inside the getBlogPost() method.

BlogService.java
@Get("/blogs")
public void getBlogPost(@Param int id) {
  BlogPost blogPost = blogPosts.get(id);
}

4. Return response

Let's return a response for the service call.

To return a response for getting a single post:

  1. Replace the return type of the getBlogPost() method from void to HttpResponse.
  2. Return a response using Armeria's HttpResponse containing the content of the blog post retrieved.
BlogService.java
import com.linecorp.armeria.common.HttpResponse;

public final class BlogService {
  @Get("/blogs/:id")
  public HttpResponse getBlogPost(@Param int id) {
    ...

    return HttpResponse.ofJson(blogPost);
  }
}

5. Test retrieving a single post

Let's test if we can retrieve a blog post we created.

  1. In the BlogServiceTest class, add a test method to retrieve the first blog post with ID 0.

    BlogServiceTest.java
    @Test
    void getBlogPost() throws JsonProcessingException {
      final WebClient client = WebClient.of(server.httpUri());
      final AggregatedHttpResponse res = client.get("/blogs/0").aggregate().join();
      final Map<String, Object> expected = Map.of("id", 0,
                  "title", "My first blog",
                  "content", "Hello Armeria!");
    
      assertThatJson(res.contentUtf8()).whenIgnoringPaths("createdAt", "modifiedAt")
                  .isEqualTo(mapper.writeValueAsString(expected));
    }
  2. Add annotations to configure the order our test methods will be executed. The annotations guarantee that the first blog post will be created in the createBlogPost() method before we try to retrieve it in the getBlogPost() method.

    BlogServiceTest.java
    import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
    import org.junit.jupiter.api.Order;
    import org.junit.jupiter.api.TestMethodOrder;
    
    @TestMethodOrder(OrderAnnotation.class) // Add this
    class BlogServiceTest {
      ...
    
      @Test
      @Order(1) // Add this
      void createBlogPost() throws JsonProcessingException {
        ...
      }
    
      @Test
      @Order(2) // Add this
      void getBlogPost() throws JsonProcessingException {
        ...
      }
    }
  3. Run all the test cases on your IDE or using Gradle.

    Your client retrieved a blog post from the server successfully if the test is passed.

6. Test retrieving multiple posts

Finally, let's test if we can retrieve multiple posts. Add a test method like the following to create the second blog post and test retrieving the list of blog posts.

BlogServiceTest.java
import java.util.List;

@Test
@Order(3)
void getBlogPosts() throws JsonProcessingException {
  final WebClient client = WebClient.of(server.httpUri());
  final HttpRequest request = createBlogPostRequest(Map.of("title", "My second blog",
                "content", "Armeria is awesome!"));
  client.execute(request).aggregate().join();
  final AggregatedHttpResponse res = client.get("/blogs").aggregate().join();
  final List<Map<String, Object>> expected = List.of(
          Map.of("id", 1,
                 "title", "My second blog",
                 "content", "Armeria is awesome!"),
          Map.of("id", 0,
                 "title", "My first blog",
                 "content", "Hello Armeria!"));
  assertThatJson(res.contentUtf8()).whenIgnoringPaths("[*].createdAt", "[*].modifiedAt")
                .isEqualTo(mapper.writeValueAsString(expected));
}

Run all the test cases on your IDE or using Gradle. Check that you see the test is passed.

You can test this also with Armeria's Documentation service. See Using DocService after adding service methods for instructions.

Next step

In this step, we've implemented methods for a READ operation and used Armeria's annotations; @Get, @ProducesJson, @Param, and @Default.

Next, at Step 6. Implement UPDATE, we'll implement an UPDATE operation to modify existing blog posts.