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:
- Access http://localhost:8080/h2-console in your web browser.
- Enter JDBC URL:
jdbc:h2:mem:testdb
and click the Connect button.
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.