Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 18

Request Body to Controller with DTO

This lesson is built with resources from youtube.com, javacodegeeks.com and 1 more site.

Hello! In our last lesson, we established a crucial pattern for building clean APIs by defining a PostDto as our response contract. This ensures our API's output is stable, secure, and decoupled from our internal data models.

Today, we'll complete the data flow by handling the input side. This lesson focuses on the learning outcome: Pass data from a request body to a controller method using a DTO and the @RequestBody annotation. We'll implement the "Create" part of our blog's CRUD functionality, allowing clients to send data to our server to create a new post.

This is a fundamental skill for any backend developer, as it's how you'll receive data for nearly every POST and PUT operation in a RESTful service.

1. From req.body to @RequestBody: A MERN Comparison

In your experience with Express.js, you're used to handling incoming JSON data like this:

// Express.js
app.use(express.json()); // Middleware to parse JSON bodies

app.post('/api/posts', (req, res) => {
  const { title, content } = req.body; // req.body is a JavaScript object
  // ... logic to create a post
});

The express.json() middleware parses the raw JSON string from the request body and populates the req.body object.

Spring Boot uses a more explicit and strongly-typed approach with the @RequestBody annotation.

  • @RequestBody tells Spring's DispatcherServlet to take the entire HTTP request body (which we'll send as a JSON string) and use a built-in library (called Jackson) to convert it into a Java object of a specific type you define. This process is called deserialization.

This gives you two immediate advantages over the typical JavaScript approach:

  1. Automatic Type Safety: If the client sends a JSON structure that doesn't match your Java DTO (e.g., a string where a number is expected), Spring will automatically reject the request with a 400 Bad Request error. You get this validation for free, before your code even runs.
  2. Explicit Contracts: It forces you to define a clear, reusable Java class (our DTO) for the request payload, making your API contract formal and self-documenting.
Client-Server Interaction with @RequestBody and @ResponseBody
This diagram illustrates the flow. The client sends a JSON payload in an HTTP POST request. On the server, `@RequestBody` handles the deserialization of this JSON into a Java object (our DTO). The reverse happens for responses.

2. Hands-On: Creating a POST Endpoint

Let's build the endpoint to create a new blog post. We'll follow the "DTO in, DTO out" pattern: the controller will accept a Request DTO and return a Response DTO.

Step 1: Define the CreatePostRequest DTO

First, we need a DTO that defines the contract for creating a post. A client should only provide the title and content. They should not be ableto set the id or createdAt timestamp.

  1. In your com.blogplatform.dto package, create a new Java record named CreatePostRequest.
// src/main/java/com/blogplatform/dto/CreatePostRequest.java
package com.blogplatform.dto;

public record CreatePostRequest(
    String title,
    String content
) {
}

This record is simple, immutable, and perfectly defines the data we expect from the client.

Step 2: Update the BlogService

Next, add a method to the BlogService to handle the logic of creating a post. For now, we will continue to simulate the database interaction.

  1. Open BlogService.java and add the following method:
// src/main/java/com/blogplatform/service/BlogService.java
package com.blogplatform.service;

import com.blogplatform.dto.CreatePostRequest; // Import request DTO
import com.blogplatform.dto.PostDto;
import com.blogplatform.model.Post;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong; // For generating IDs
import java.util.stream.Collectors;

@Service
public class BlogService {
    
    // Simulate a database sequence for IDs
    private final AtomicLong idCounter = new AtomicLong(3);

    public List<PostDto> getAllPosts() {
        // ... (existing method)
    }

    public PostDto createPost(CreatePostRequest request) {
        // 1. In a real app, you'd map the DTO to a JPA entity
        Post newPost = new Post(
                idCounter.getAndIncrement(), // Generate a new ID
                request.title(),
                request.content(),
                LocalDateTime.now(),
                "CREATED" // Set an internal status
        );

        // 2. You would then save the entity to the database
        System.out.println("Simulating saving post to DB: " + newPost.getTitle());

        // 3. Map the newly created entity back to a response DTO to return to the client
        return new PostDto(
                newPost.getId(),
                newPost.getTitle(),
                newPost.getContent()
        );
    }
}

Note: I've added an AtomicLong to simulate generating new unique IDs for our posts, making our simulation a bit more realistic.

Step 3: Update the BlogController

Finally, let's create the HTTP endpoint in our BlogController.

  1. Open BlogController.java and add the @PostMapping method.
// src/main/java/com/blogplatform/controller/BlogController.java
package com.blogplatform.controller;

import com.blogplatform.dto.CreatePostRequest; // Import request DTO
import com.blogplatform.dto.PostDto;
import com.blogplatform.service.BlogService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*; // Import ResponseStatus

import java.util.List;

@RestController
@RequestMapping("/api/posts") // Set a base path for all endpoints in this controller
public class BlogController {

    private final BlogService blogService;

    public BlogController(BlogService blogService) {
        this.blogService = blogService;
    }

    @GetMapping
    public List<PostDto> getAllPosts() {
        return blogService.getAllPosts();
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED) // Set the HTTP status code for a successful creation
    public PostDto createPost(@RequestBody CreatePostRequest request) {
        return blogService.createPost(request);
    }
}

Notice a few key details:

  • @RequestMapping("/api/posts") at the class level provides a base URL for all methods in this controller. This is cleaner than repeating the path on each method.
  • @PostMapping: This annotation maps HTTP POST requests to this method. Since we didn't specify a path, it maps to the base path /api/posts.
  • @RequestBody CreatePostRequest request: This is the core of our lesson. It tells Spring to take the JSON body and turn it into a CreatePostRequest object.
  • @ResponseStatus(HttpStatus.CREATED): A best practice for POST requests that create a resource is to return an HTTP 201 Created status code. This annotation handles that for us.

3. Testing with curl

Restart your application. Now, open your terminal and use curl to send a POST request with a JSON body.

curl -X POST http://localhost:8080/api/posts \
-H "Content-Type: application/json" \
-d '{
    "title": "API Input with DTOs",
    "content": "This is how we send data to a Spring Boot API."
}'

You should receive a response like this, with an HTTP 201 Created status:

{
  "id": 3,
  "title": "API Input with DTOs",
  "content": "This is how we send data to a Spring Boot API."
}

You have successfully sent data to your application, which was deserialized into a DTO and processed by your service.


4. Debugging Task: Observe Deserialization in Action

Let's see this process happen in real-time.

  1. In BlogController.java, place a breakpoint on the line return blogService.createPost(request); inside your new createPost method.
  2. Run the application in Debug Mode.
  3. Execute the same curl command again (or use an API client like Postman).
  4. Your IDE will pause at the breakpoint. In the debugger's "Variables" pane, expand the request object.
  5. You will see an instance of CreatePostRequest with its title and content fields populated with the exact data you sent in the JSON body.

This is a powerful visual confirmation of how @RequestBody works. Spring and the Jackson library handled the entire complex process of parsing the text-based JSON and constructing a strongly-typed Java object for you.


5. A Glimpse into Validation

Right now, our endpoint would accept a request with an empty title or content. This is not robust.

{ "title": "", "content": null }

In a Node.js project, you'd add a library like zod or joi to validate the req.body. Spring has a similar, built-in mechanism called Bean Validation. To use it, we first need to add the dependency.

Open your pom.xml and add the validation starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Your IDE should prompt you to reload your Maven dependencies. Now, let's watch a short clip that demonstrates how to apply this.

Spring Boot Best Practices For Developers 👨‍💻 | Productivity | JavaTechie

The video 'Spring Boot Best Practices For Developers' from Java Techie provides a clear, hands-on demonstration of how to add validation rules directly to a DTO.

Watch from 33:15 to 36:46. Pay close attention to how annotations like @NotBlank are added to the DTO fields, and how the @Valid annotation is added in the controller next to @RequestBody. This is the standard pattern for enabling input validation.

As the video shows, by adding annotations like @NotBlank to your DTO and @Valid to your controller method, you can enforce business rules automatically. We will dive deep into this and global error handling in Module 5, but it's important to see how naturally it connects to the DTO pattern.


Conclusion

Fantastic work! You have now mastered both sides of the API data contract. You can accept structured input with Request DTOs and provide structured output with Response DTOs.

Key Takeaways:

  • The @RequestBody annotation is used to deserialize an HTTP request body (e.g., JSON) into a Java object.
  • Request DTOs define a strict, secure contract for the data a client is allowed to send when creating or updating a resource.
  • Combining @PostMapping with @RequestBody is the standard way to implement "Create" endpoints in Spring Boot.
  • Following a "DTO in, DTO out" pattern in your controllers leads to clean, decoupled, and secure application layers.

Preview of the Next Lesson:
Our GET /api/posts endpoint currently returns all posts at once. What happens when we have thousands of posts? The response would be huge and slow. In the next lesson, we will solve this by learning how to implement pagination and sorting for list endpoints using Spring Data's Pageable interface, a crucial feature for any production-ready API.