Working with HTTP requests in Spring Boot

olnov

olnov

Posted on October 6, 2024

Working with HTTP requests in Spring Boot

Hello world!
The main goal of this article is to help beginner developers handle HTTP requests in Spring Boot.

💡In the examples I do not cover all the code required for the MVC app, just some parts to demonstrate the difference in data processing.

Recently, I’ve been working on an engineering project with other students in my class. It introduced us to a new technology stack, as we were required to build upon an “old” codebase. The codebase included Java, Spring Boot, and Thymeleaf. The project's aim was to create a clone of a popular social network.
The core functionality was fairly typical: users can create posts, and others can comment on or like those posts.
To add some visual dynamism, we decided to combine Thymeleaf with JavaScript. This way, when a post is displayed on the page, users can click to like or comment, and the changes will be processed in the back end. At this point, we needed a JavaScript function to send requests to the server for all the standard CRUD operations.
The question was: how do we properly pass data to the server using POST, PUT, or DELETE methods? GET is more or less clear, so I skip examples with GET.
Here are the possible ways.

URL Parameters (PathVariable)

URL Example: HTTP://myapp.com/posts/1

Suitable for: DELETE, PUT

Cases: You work with a specific entity on a back end - a single post in my examples.

Annotation Example:

@DeleteMapping("/posts/{post_id}")
public ResponseEntity<String> deletePost(@PathVariable("post_id") Long post_id) {
        // Some logic here...
        return ResponseEntity.ok("Deleted successfully");
    }
Enter fullscreen mode Exit fullscreen mode

Example of a corresponding JS code:

 // Some pre-logic here to pass postId to the function, 
// or you can use const deletePost = async(postId)=>{} to pass postId directly
const deletePost = async () => {
    // Some pre-checks and error handling go here...
    const requestOption = {
        method:'DELETE',
        headers:{
            'Content-type':'application/json'
        }
    };
    await fetch(`/posts/${postId}`, requestOptions);
    // Some post-checks and error handling go here...
}
Enter fullscreen mode Exit fullscreen mode

Form data (RequestParam)

URL Example: HTTP://myapp.com/posts or HTTP://myapp.com/posts/1 for editing

Suitable for: PUT, POST

Cases: You are creating or updating an entity with one or two parameters. In my example, it’s a post content (a text message).

Annotation Example:

@PutMapping("/posts/{post_id}")
    public ResponseEntity<String> editPost(@PathVariable("post_id") Long post_id, @RequestParam("content") String content) {
        // Some logic goes here...
        return ResponseEntity.ok("Post updated successfully");
    }
Enter fullscreen mode Exit fullscreen mode

Example of a corresponding JS code:

// Some pre-logic here to pass postId and content to the function, 
// or you can use const deletePost = async(postId, updatedContent)=>{} to pass 
// them directly directly
const updatePost = async ()=> {
    // Some pre-checks and error handling go here...
    const formData = new FormData();
    formData.append("content",updatedContent);
    requestOptions = {
        method:'PUT',
        body: formData
    };
    await fetch(`/posts/${postId}`,requestOptions);
    // Some post-checks and error handling go here...
}
Enter fullscreen mode Exit fullscreen mode

JSON Body (RequestBody)

Suitable for: PUT, POST

Cases: You are creating or updating a complex entity (e.g. object with 3 or more parameters).

Annotation Example:

@PutMapping("/posts/{post_id}")
    public ResponseEntity<String> editPost(@PathVariable("post_id") Long post_id, @RequestBody Post post) {
        // Some logic goes here...
        // It requires the whole object to be passed. 
        // After that it's possible to access values via getters of your object's model
        return ResponseEntity.ok("Post updated successfully");
    }
Enter fullscreen mode Exit fullscreen mode

Example of a corresponding JS code:

const updatePost = async ()=> {
    // Some pre-checks and error handling go here...
    requestOptions = {
        method:'PUT',
        headers: {
            'Content-type':'application/json'
        },
        body: JSON.stringify({'content':updatedContent})
    };
    await fetch(`/posts/${postId}`,requestOptions);
    // Some post-checks and error handling go here...
}
Enter fullscreen mode Exit fullscreen mode

This is it. Hope it will be helpful.
Cheers!

💖 💪 🙅 🚩
olnov
olnov

Posted on October 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related