Spring Boot Backend Development Course, Blog Creation Example, Implementing API for Retrieving Blog Post List

In this course, we will look at how to implement an API for retrieving a list of blog posts using Spring Boot. Spring Boot is a framework that maximizes productivity, making it easy to set up and configure so that developers can focus on their core business logic. This course will guide you step by step through the process of designing and implementing the basic API for a blog.

1. Introduction to Spring Boot

Spring Boot is a lightweight application framework based on the Spring Framework. It is commonly used for implementing microservice architecture and helps developers quickly set up and deploy applications. The advantages of Spring Boot are as follows:

  • Auto-configuration: Developers can start projects with minimal configuration.
  • Dependency management: Libraries can be managed easily through Maven or Gradle.
  • Embedded server: Applications can be run easily without separate server installations.

2. Project Preparation

2.1. Development Environment

This course uses the following development environment:

  • Java 11 or higher
  • Spring Boot 2.x
  • Spring Data JPA
  • H2 Database (in-memory database for development)
  • IDEs: IntelliJ IDEA or Eclipse

2.2. Creating the Project

Access Spring Initializr (https://start.spring.io/) to create a new project. Add the following dependencies:

  • Spring Web
  • Spring Data JPA
  • H2 Database

Enter other required information such as the project name and package name, then download it as a ZIP file and import it into your IDE.

3. Data Modeling

To retrieve the list of blog posts, we need to define an HTML Post entity that represents a blog post.

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String content;
    private String author;
    private LocalDateTime createdAt;

    // Getters and Setters omitted for brevity.
}

4. Implementing the Repository Layer

To interact with the database, we will create a repository interface using JPA.

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PostRepository extends JpaRepository {
}

5. Implementing the Service Layer

We need to create a service class to handle business logic.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PostService {
    @Autowired
    private PostRepository postRepository;

    public List getAllPosts() {
        return postRepository.findAll();
    }

    // Additional methods can be added here for more functionalities
}

6. Implementing the Controller

We will create a controller class to implement the REST API to handle client requests.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class PostController {
    @Autowired
    private PostService postService;

    @GetMapping("/api/posts")
    public ResponseEntity> getAllPosts() {
        List posts = postService.getAllPosts();
        return ResponseEntity.ok(posts);
    }
}

7. Running the Application

Now that all components are ready, you can run the application from the application class that contains the `main` method.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BlogApplication {
    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
}

8. Testing the API

To test whether the API works properly, you can use Postman or cURL. Send a GET request to `/api/posts` to check the result.

9. Database Initialization

To facilitate testing, you can add some dummy data to the database. You can initialize data using the following method.

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DataInitializer {

    @Autowired
    private PostRepository postRepository;

    @PostConstruct
    public void init() {
        Post post1 = new Post();
        post1.setTitle("First Blog Post");
        post1.setContent("Content of the blog post...");
        post1.setAuthor("Author1");
        post1.setCreatedAt(LocalDateTime.now());

        Post post2 = new Post();
        post2.setTitle("Second Blog Post");
        post2.setContent("Content of the blog post...");
        post2.setAuthor("Author2");
        post2.setCreatedAt(LocalDateTime.now());

        postRepository.save(post1);
        postRepository.save(post2);
    }
}

10. Conclusion

In this course, we implemented a simple API for retrieving a list of blog posts using Spring Boot. This API retrieves blog posts from the database and returns them to the client in JSON format. In the future, you can learn to implement CRUD (Create, Read, Update, Delete) functionalities, security, deployment, and more.

Using Spring Boot makes backend development simpler and more efficient, and it is a framework chosen by many developers due to its various features and ecosystem. I hope you continue to enhance your development skills through ongoing learning and practice.

References

Spring Boot Backend Development Course, Blog Creation Example, Implementing an API to Retrieve Blog Post List

Hello! In this tutorial, we will learn how to develop a simple blog application using Spring Boot. Specifically, we will look at the process of implementing an API to retrieve a list of blog posts step by step. Through this tutorial, you will understand the basic components of Spring Boot and the principles of RESTful API design, and learn how to apply them in real practice.

1. Introduction to Spring Boot

Spring Boot is part of the Spring framework, which is a Java-based web framework that helps developers quickly build new applications. Spring Boot minimizes complex configurations and allows you to easily add necessary features through dependency injection. It leverages the powerful capabilities of Spring while providing a simpler development experience.

2. Project Setup

First, you need to create a Spring Boot project. You can use Spring Initializr for this.

  1. Basic Settings
    Since the interface of the web page is constructed through a RESTful API, add the ‘Spring Web’ dependency. Add ‘Spring Data JPA’ for business logic and ‘H2 Database’ for connecting to the database.
  2. Project Metadata
    Group: com.example
    Artifact: blog
  3. Java Version
    Set to use Java 11 or higher.

3. Basic Directory Structure

Open the created project in your IDE (e.g., IntelliJ IDEA) and check the basic directory structure. The project will have the following structure.

blog
│
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── blog
│   │   │               ├── BlogApplication.java
│   │   │               ├── model
│   │   │               ├── repository
│   │   │               ├── service
│   │   │               └── controller
│   │   └── resources
│   │       ├── application.properties
│   │       └── static
│   └── test
└── pom.xml

4. Defining the Domain Model

We define a domain model that represents a blog post. This model should include the title, content, author, created date, etc.

package com.example.blog.model;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String content;
    private String author;
    
    private LocalDateTime createdDate;

    // getters and setters
}

5. Implementing JPA Repository

Define an interface so that we can access the database through the JPA Repository. It should include a method to retrieve the list of blog posts.

package com.example.blog.repository;

import com.example.blog.model.Post;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PostRepository extends JpaRepository {
    List findAll();
}

6. Implementing the Service Layer

Create a service layer to implement the class that handles business logic. Here, we will create a method to retrieve the list of posts as an example.

package com.example.blog.service;

import com.example.blog.model.Post;
import com.example.blog.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PostService {
    @Autowired
    private PostRepository postRepository;

    public List getAllPosts() {
        return postRepository.findAll();
    }
}

7. Implementing the Controller

Create a controller for the RESTful API to handle client requests. Here, we will create an API to retrieve a list of blog posts through an HTTP GET request.

package com.example.blog.controller;

import com.example.blog.model.Post;
import com.example.blog.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/posts")
public class PostController {
    @Autowired
    private PostService postService;

    @GetMapping
    public ResponseEntity> getAllPosts() {
        List posts = postService.getAllPosts();
        return ResponseEntity.ok(posts);
    }
}

8. Application Properties Settings

Add the configuration for the database connection to the application.properties file. We will use the H2 database as a sample.

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update

9. Running and Testing the Application

Now, let’s run the application and test the getAllPosts API in the PostController. You can send a request using Postman or curl like below.

GET http://localhost:8080/api/posts

The above GET request should return the pre-entered list of posts.

10. Conclusion

In this tutorial, we implemented a simple blog post list retrieval API using Spring Boot. Through this process, we learned the basic structure of Spring Boot and the principles of RESTful API design. Additionally, implementing user authentication and CRUD functionalities would be a good way to advance further.

Continue to develop your blog project by exploring more Spring Boot related materials!

Spring Boot Backend Development Course, Blog Production Example, Repository Creation

1. Introduction

Spring Boot is a Java-based framework that helps to develop applications quickly and easily. This course explains the core concepts and technologies needed to build a blog web application using Spring Boot. You will cover topics such as database integration, REST API design, and communication with the frontend.

1.1. Course Objectives

  • Understanding the basic concepts of Spring Boot
  • Designing and implementing RESTful APIs
  • Learning how to integrate with databases using JPA
  • User authentication and authorization management using Spring Security
  • Implementing functionalities through communication with the frontend

2. Environment Setup

To develop a Spring Boot application, the following development environment is required.

2.1. Prerequisites

  • Java 11 or higher
  • Spring Boot 2.5 or higher
  • Maven or Gradle (dependency management tools)
  • IDE (IntelliJ IDEA, Eclipse, etc.)

2.2. Setting Up the Development Environment

Follow the steps below to set up the development environment. Install the JAVA JDK, then install the IDE and add the required plugins and libraries.

3. Creating a Spring Boot Project

There are many ways to create a Spring Boot project, but the simplest method is to use Spring Initializr.

3.1. Creating a Project Using Spring Initializr

  1. Open the Spring Initializr page in your web browser.
  2. Set up the project metadata.
  3. Project

    Select Maven Project or Gradle Project

  4. Language

    Select Java

  5. Spring Boot

    Select the latest stable version

  6. Project Metadata

    Set the Group and Artifact.

  7. Dependencies

    Add Web, JPA, H2 Database, Security.

  8. Click the Generate button to download the project.

4. Understanding the Project Structure

The structure of a Spring Boot project is the same as a typical Maven project, but there are some differences according to Spring Boot’s conventions. Below is the basic project structure.

        └── demo
            ├── DemoApplication.java
            ├── controller
            ├── model
            ├── repository
            └── service
    

4.1. Description of Main Packages

  • controller: Contains controller classes that handle web requests.
  • service: Contains service classes that implement business logic.
  • repository: Contains repository classes responsible for interacting with the database.
  • model: Contains classes that define database entities.

5. Designing the Blog Domain Model

Define the domain model for the blog application. This model includes Post and User entities.

5.1. Post Entity


    @Entity
    public class Post {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String title;
        private String content;
        
        @ManyToOne
        private User author;

        // Getters and Setters
    }
    

5.2. User Entity


    @Entity
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String username;
        private String password;

        @OneToMany(mappedBy = "author")
        private List posts;

        // Getters and Setters
    }
    

6. Creating Repository Interfaces

Create repository interfaces to access the database using JPA. With Spring Data JPA, CRUD operations can be performed easily.

6.1. PostRepository


    public interface PostRepository extends JpaRepository {
    }
    

6.2. UserRepository


    public interface UserRepository extends JpaRepository {
        Optional findByUsername(String username);
    }
    

7. Implementing Services

Implement the service layer to handle business logic. The service calls the repositories to perform DB operations and apply necessary business rules.

7.1. PostService


    @Service
    public class PostService {
        @Autowired
        private PostRepository postRepository;

        public List getAllPosts() {
            return postRepository.findAll();
        }

        public Post createPost(Post post) {
            return postRepository.save(post);
        }
    }
    

7.2. UserService


    @Service
    public class UserService {
        @Autowired
        private UserRepository userRepository;

        public User findUserByUsername(String username) {
            return userRepository.findByUsername(username).orElse(null);
        }

        public User createUser(User user) {
            return userRepository.save(user);
        }
    }
    

8. Implementing Controllers

Implement controllers to handle user requests. Design RESTful web services to manage communication between clients and servers.

8.1. PostController


    @RestController
    @RequestMapping("/api/posts")
    public class PostController {
        @Autowired
        private PostService postService;

        @GetMapping
        public List getAllPosts() {
            return postService.getAllPosts();
        }

        @PostMapping
        public Post createPost(@RequestBody Post post) {
            return postService.createPost(post);
        }
    }
    

8.2. UserController


    @RestController
    @RequestMapping("/api/users")
    public class UserController {
        @Autowired
        private UserService userService;

        @PostMapping
        public User createUser(@RequestBody User user) {
            return userService.createUser(user);
        }

        @GetMapping("/{username}")
        public User getUserByUsername(@PathVariable String username) {
            return userService.findUserByUsername(username);
        }
    }
    

9. Configuring Spring Security

Set up Spring Security for user authentication and authorization management. Configure the base security settings to protect URLs and user authentication mechanisms.


    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                .antMatchers("/api/users").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin();
        }
    }
    

10. Running and Testing the Application

Now you’re ready to run the application and test the API using tools like Postman. Make sure each endpoint works correctly.

10.1. Running the Application

For IntelliJ IDEA, you can run the application by clicking the Run icon in the main class or execute the following command in the command line.

./mvnw spring-boot:run

10.2. Testing with Postman

You can test the REST API using Postman. Here are some basic testing examples.

  • GET /api/posts: Retrieve all posts
  • POST /api/posts: Create a new post
  • GET /api/users/{username}: Retrieve information for a specific user
  • POST /api/users: Create a new user

11. Conclusion

Through this course, you learned how to build a simple blog application using Spring Boot. This example allowed you to cover various topics such as REST API design, database integration, and implementation of services and controllers. Going forward, try to challenge yourself to develop more complex applications based on this foundation.

12. References

Spring Boot Backend Development Course, Blog Creation Example, Writing Test Code to Reduce Repetitive Tasks

In this course, you will learn how to create a blog using Spring Boot, and we will explore how to write test code that will reduce repetitive tasks. This blog project is one of the best ways to practically learn and will further enhance your skills as a developer. The course content is aimed at everyone from beginners to intermediate learners.

1. Introduction to Spring Boot

Spring Boot is a simplified configuration of the Spring Framework that helps you develop Spring applications quickly and easily. Using Spring Boot minimizes complex setups or XML configurations and offers the advantage of integrating various embedded servers.

1.1 Advantages of Spring Boot

  • Quick Start: You can quickly run simple applications using pre-configured templates.
  • Auto Configuration: Spring Boot automatically sets up the components of your application.
  • Embedded Servers: You can run applications without separate server installations using embedded servers like Tomcat and Jetty.
  • Dependency Management: Managing dependencies through Maven or Gradle is easy.

2. Project Environment Setup

Now let’s set up the environment to create the actual blog application. You can configure the project using the Spring Initializr.

2.1 Using Spring Initializr

  1. Go to Spring Initializr in your web browser.
  2. Enter the project metadata:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: Select the latest version
    • Group: com.example
    • Artifact: blog
    • Name: blog
    • Package name: com.example.blog
  3. Select the following in Dependencies:
    • Spring Web
    • Spring Data JPA
    • H2 Database (can be switched to MySQL)
    • Spring Boot DevTools
  4. Click the Generate button to download the ZIP file.

3. Blog Application Structure

After configuring the project, we will look at the application structure. A proper directory structure enhances maintainability and readability.

3.1 Directory Structure

    blog
    ├── src
    │   ├── main
    │   │   ├── java
    │   │   │   └── com
    │   │   │       └── example
    │   │   │           └── blog
    │   │   │               ├── BlogApplication.java
    │   │   │               ├── controller
    │   │   │               ├── model
    │   │   │               └── repository
    │   │   └── resources
    │   │       ├── application.properties
    │   │       └── static
    │   │           └── ...
    └── test

4. Creating Basic Models and Repositories

Now, we will create the basic model classes and repository for the blog. The model represents a blog post, while the repository interacts with the database.

4.1 Creating the Model Class

First, we create the BlogPost model class.

    package com.example.blog.model;

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Column;
    import java.time.LocalDateTime;

    @Entity
    public class BlogPost {
        
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;

        @Column(nullable = false)
        private String title;

        @Column(nullable = false, length = 5000)
        private String content;

        private LocalDateTime createdAt;

        public BlogPost() {
            this.createdAt = LocalDateTime.now();
        }

        // Getters and Setters
    }

4.2 Creating the Repository Interface

Next, we create the BlogPostRepository interface to utilize JPA’s CRUD functionalities.

    package com.example.blog.repository;

    import com.example.blog.model.BlogPost;
    import org.springframework.data.jpa.repository.JpaRepository;

    public interface BlogPostRepository extends JpaRepository {
    }

5. Creating Controllers and Implementing REST API

We will create a REST API to manage the data of blog posts. To do this, we will write the controller class.

5.1 Creating the REST Controller

    package com.example.blog.controller;

    import com.example.blog.model.BlogPost;
    import com.example.blog.repository.BlogPostRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;

    import java.util.List;

    @RestController
    @RequestMapping("/api/posts")
    public class BlogPostController {

        @Autowired
        private BlogPostRepository blogPostRepository;

        @GetMapping
        public List getAllPosts() {
            return blogPostRepository.findAll();
        }

        @PostMapping
        public BlogPost createPost(@RequestBody BlogPost blogPost) {
            return blogPostRepository.save(blogPost);
        }

        @GetMapping("/{id}")
        public ResponseEntity getPostById(@PathVariable Long id) {
            return blogPostRepository.findById(id)
                    .map(post -> ResponseEntity.ok().body(post))
                    .orElse(ResponseEntity.notFound().build());
        }
        
        // Additional Update and Delete methods
    }

6. Writing Test Code

In this section, we will write test code to verify that the REST API we created works correctly. Spring Boot allows for easy testing using JUnit and Mockito.

6.1 Setting Up the Test Environment

    
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

6.2 Example of Testing the REST API

    package com.example.blog;

    import com.example.blog.model.BlogPost;
    import com.example.blog.repository.BlogPostRepository;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.http.MediaType;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

    @SpringBootTest
    @AutoConfigureMockMvc
    public class BlogPostControllerTest {

        @Autowired
        private MockMvc mockMvc;

        @Autowired
        private BlogPostRepository blogPostRepository;

        private ObjectMapper objectMapper;

        @BeforeEach
        public void setUp() {
            objectMapper = new ObjectMapper();
            blogPostRepository.deleteAll();
        }

        @Test
        public void createPost_ShouldReturnCreatedPost() throws Exception {
            BlogPost post = new BlogPost();
            post.setTitle("Title");
            post.setContent("Body content");

            mockMvc.perform(post("/api/posts")
                    .content(objectMapper.writeValueAsString(post))
                    .contentType(MediaType.APPLICATION_JSON))
                    .andExpect(MockMvcResultMatchers.status().isCreated());
        }
        
        // Additional method tests
    }

7. Running the Project

You are now ready to run the blog application. By running the BlogApplication.java file in your IDE, the embedded server will start, and you can use the REST API.

7.1 Testing the API with Postman

You can use API testing tools like Postman to test the REST API you created. Experience adding and retrieving blog posts through POST and GET requests.

Conclusion

In this Spring Boot backend development course, we learned the core features of Spring Boot by developing a simple blog application. We experienced interactions with the database through basic CRUD operations and learned ways to make the development process more efficient by writing test code.

Based on this project, feel free to add more features and improve the design to evolve into a more complete blog application. We hope you continue to take on new features and frameworks in the future. Thank you.

Spring Boot Backend Development Course, Blog Production Example, Testing API Execution

Spring Boot is a framework that allows for fast and easy development of web applications based on Java. In this course, we will build a backend server using Spring Boot and implement a RESTful API through a blog creation example. Finally, we will also learn how to test the API execution.

1. Introduction to Spring Boot

Spring Boot is a technology that enables easy and rapid application development based on the Spring Framework. Using Spring Boot reduces complex configurations and allows for easy testing through an embedded server.

  • Auto-configuration: Automatically performs basic configurations to reduce the need for developers to worry about settings.
  • Embedded server: Supports embedded servers like Tomcat and Jetty, allowing development and testing without separate server installation.
  • Starter dependencies: Provides starter dependencies that help easily add various functionalities.

2. Setting up the Development Environment

To use Spring Boot, you need a Java Development Kit (JDK) and a build tool like Maven or Gradle. Below are the installation methods for JDK and Maven.

2.1 Installing JDK

Install JDK version 8 or higher. You can download it from Oracle’s official website. After installation, check the installed version using the command below:

java -version

2.2 Installing Maven

Maven is used to manage the dependencies of Spring Boot projects. Download and install it from the official Apache Maven website. After installation, check the installed version using the command below:

mvn -version

2.3 Choosing an IDE

You can use IDEs such as IntelliJ IDEA, Eclipse, or Spring Tool Suite (STS). This course will explain using IntelliJ IDEA as the basis.

3. Creating a Spring Boot Project

A Spring Boot project can be easily created using Spring Initializr. Spring Initializr is a web application that automatically generates the basic structure of a Spring Boot application.

3.1 Accessing Spring Initializr

Access Spring Initializr through the link below:
Spring Initializr

3.2 Project Configuration

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Select the latest version
  • Group: com.example
  • Artifact: blog-api
  • Name: blog-api
  • Description: Blog API example
  • Package name: com.example.blogapi
  • Packaging: Jar
  • Java: Select 11

3.3 Adding Dependencies

Add the necessary dependencies. Add the following dependencies:

  • Spring Web
  • Spring Data JPA
  • H2 Database (or MySQL can be selected)

After setting up, click the GENERATE button to download the ZIP file and unzip it in your desired location.

4. Understanding the Project Structure

The generated project folder structure is as follows:


blog-api
 ├── src
 │    ├── main
 │    │    ├── java
 │    │    │    └── com
 │    │    │         └── example
 │    │    │              └── blogapi
 │    │    │                   └── BlogApiApplication.java
 │    │    └── resources
 │    │         ├── application.properties
 │    │         └── static
 │    └── test
 ├── pom.xml

5. Creating a Domain Object

Now, let’s create a domain object to represent a blog post. We will create a Post class to define the attributes of the blog post.

5.1 Creating the Post Class

Create a Post.java file in the src/main/java/com/example/blogapi folder:


package com.example.blogapi;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String content;

    // getters and setters
}

6. Creating a Repository Interface

To interact with the database, we will use a JPA repository. Create a PostRepository interface to implement CRUD functionality.

6.1 Creating the PostRepository Interface

Create a PostRepository.java file in the src/main/java/com/example/blogapi folder:


package com.example.blogapi;

import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository {
}

7. Creating a Service Class

Create a service class to handle business logic. We will create a PostService class to implement CRUD functionality for blog posts.

7.1 Creating the PostService Class

Create a PostService.java file in the src/main/java/com/example/blogapi folder:


package com.example.blogapi;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class PostService {
    @Autowired
    private PostRepository postRepository;

    public List getAllPosts() {
        return postRepository.findAll();
    }

    public Post getPostById(Long id) {
        return postRepository.findById(id).orElse(null);
    }

    public Post createPost(Post post) {
        return postRepository.save(post);
    }

    public Post updatePost(Long id, Post post) {
        Post existingPost = postRepository.findById(id).orElse(null);
        if (existingPost != null) {
            existingPost.setTitle(post.getTitle());
            existingPost.setContent(post.getContent());
            return postRepository.save(existingPost);
        }
        return null;
    }

    public void deletePost(Long id) {
        postRepository.deleteById(id);
    }
}

8. Creating a Controller Class

To handle requests from clients, we write a controller class to create a RESTful API.

8.1 Creating the PostController Class

Create a PostController.java file in the src/main/java/com/example/blogapi folder:


package com.example.blogapi;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/posts")
public class PostController {
    @Autowired
    private PostService postService;

    @GetMapping
    public List getAllPosts() {
        return postService.getAllPosts();
    }

    @GetMapping("/{id}")
    public Post getPostById(@PathVariable Long id) {
        return postService.getPostById(id);
    }

    @PostMapping
    public Post createPost(@RequestBody Post post) {
        return postService.createPost(post);
    }

    @PutMapping("/{id}")
    public Post updatePost(@PathVariable Long id, @RequestBody Post post) {
        return postService.updatePost(id, post);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deletePost(@PathVariable Long id) {
        postService.deletePost(id);
    }
}

9. Configuring Application Properties

Edit the application.properties file to configure database connection and other settings.

9.1 H2 Database Configuration

Edit the src/main/resources/application.properties file as follows:


# H2 Database
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

10. Running the Application

Now that all configurations are complete, run the BlogApiApplication.java class in your IDE to start the application.

10.1 Accessing the H2 Console

If the application is running successfully, you can access the H2 console to check the database:

11. Testing the API

Now let’s test the API using Postman or cURL.

11.1 Installing Postman

Postman is a useful tool for testing APIs. After installing Postman, you can send requests as shown below.

11.2 API Request Examples

  • GET /api/posts: Retrieve all posts
  • GET /api/posts/{id}: Retrieve a specific post
  • POST /api/posts: Create a post
  • PUT /api/posts/{id}: Update a post
  • DELETE /api/posts/{id}: Delete a post

11.2.1 Example of a POST Request:


POST /api/posts
Content-Type: application/json

{
    "title": "First Post",
    "content": "Hello, this is the first post."
}

11.2.2 Example of a GET Request:


GET /api/posts

12. Conclusion

In this course, we learned how to implement a simple blog API using Spring Boot. We set up domain objects, repositories, services, and controllers, and examined the process of testing the API using Postman.

Now you have laid the foundation to create a blog API using Spring Boot. You can expand your knowledge by implementing more features, transitioning to different databases, learning about deployment methods, and more.

References