Building a REST API with Spring Boot: A Step-by-Step Guide

mohamed_manbar

Mohamed Manbar

Posted on July 22, 2024

Building a REST API with Spring Boot: A Step-by-Step Guide

To create a REST API using Spring Boot and publish an article about it on Medium, here are the general steps to follow:

1. Initialize a Spring Boot Project

Step 1: Use Spring Initializr
Go to Spring Initializr.

Configure your project:

Image description

Project: Maven Project
Language: Java
Spring Boot: 3.3.x or a more recent stable version
Project Metadata: Fill in the group, artifact, and other necessary information
Dependencies: Add Spring Web, Spring Data JPA, and H2 Database (for an in-memory database)
Click โ€œGenerateโ€ to download the project.

Step 2: Unzip and Import the Project
Unzip the downloaded ZIP file.
Import the project into your preferred IDE (Eclipse, IntelliJ IDEA, etc.).

2. Configure the Project

Step 3: Configure the H2 Database
In the application.properties file, add the following configurations for H2:

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=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
Enter fullscreen mode Exit fullscreen mode

Step 4: Create the JPA Entity
Create an Article class representing an article:

package com.example.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Article {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String content;
    // Getters and Setters
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Create the JPA Repository
Create an ArticleRepository interface:

package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.model.Article;
public interface ArticleRepository extends JpaRepository<Article, Long> {
}
Enter fullscreen mode Exit fullscreen mode

3. Create Services and Controllers

Step 6: Create the Service
Create an ArticleService class:

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.repository.ArticleRepository;
import com.example.demo.model.Article;
import java.util.List;
@Service
public class ArticleService {
    @Autowired
    private ArticleRepository articleRepository;
    public List<Article> getAllArticles() {
        return articleRepository.findAll();
    }
    public Article getArticleById(Long id) {
        return articleRepository.findById(id).orElse(null);
    }
    public Article saveArticle(Article article) {
        return articleRepository.save(article);
    }
    public void deleteArticle(Long id) {
        articleRepository.deleteById(id);
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 7: Create the Controller
Create an ArticleController class:

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.demo.service.ArticleService;
import com.example.demo.model.Article;
import java.util.List;
@RestController
@RequestMapping("/api/articles")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @GetMapping
    public List<Article> getAllArticles() {
        return articleService.getAllArticles();
    }
    @GetMapping("/{id}")
    public Article getArticleById(@PathVariable Long id) {
        return articleService.getArticleById(id);
    }
    @PostMapping
    public Article createArticle(@RequestBody Article article) {
        return articleService.saveArticle(article);
    }
    @DeleteMapping("/{id}")
    public void deleteArticle(@PathVariable Long id) {
        articleService.deleteArticle(id);
    }
}

Enter fullscreen mode Exit fullscreen mode

**

4. Test the Application

**
Step 8: Run the Application
Run the main class of the project (annotated with @SpringBootApplication).
Access the H2 console via http://localhost:8080/h2-console and use the configured connection details to verify the data.
Step 9: Test the Endpoints
Use tools like Postman to test the endpoints:

  • GET /api/articles: Retrieves all articles
  • GET /api/articles/{id}: Retrieves an article by ID
  • POST /api/articles: Creates a new article
  • DELETE /api/articles/{id}: Deletes an article by ID
๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
mohamed_manbar
Mohamed Manbar

Posted on July 22, 2024

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

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About