How to Build a Basic REST API with Spring Boot

Step 1: Project Setup

1. Create a new Spring Boot project:

  • Use Spring Initializr (https://start.spring.io/) to generate a project.
  • Add the following dependencies: Spring Web, Spring Data JPA, H2 Database (for in-memory database).

2. Project Structure:

  • Your project should have the following basic structure:
    • src/main/java: Contains your Java code.
    • src/main/resources: Contains configuration files.
    • src/test/java: Contains your test cases.

Step 2: Define an Entity

import javax.persistence.*;

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

    // getters and setters
}

Step 3: Create a Repository

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

public interface UserRepository extends JpaRepository<User, Long> {
}

Step 4: Create a REST Controller

import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

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

    // ... other endpoints for update, delete, etc.
}

Step 5: Run the Application

Start your Spring Boot application.

Test your API using a tool like Postman or curl.

curl -X GET http://localhost:8080/users

Explanation:

  • We’ve created a simple Spring Boot application with a User entity, a UserRepository, and a UserController.
  • The UserController exposes a GET endpoint to retrieve all users.
  • Spring Data JPA handles the database interactions through the UserRepository.

Additional Notes:

  • This is a basic example. You can add more endpoints, error handling, security, and other features to enhance your API.
  • Consider using a production-ready database like MySQL or PostgreSQL for real-world applications.
  • Implement proper data validation and error handling.
  • Explore additional Spring Boot features like configuration properties, profiles, and more.

Would you like to add more features to this API?

  • Data validation
  • Exception handling
  • Security (e.g., basic auth, JWT)
  • Database connection configuration
  • Testing

Leave a Reply

Shopping cart

0
image/svg+xml

No products in the cart.

Continue Shopping