Spring Boot — Rest API
Discover the intricacies of crafting a robust RESTful API with Spring Boot in this comprehensive guide. From tool setup using Eclipse IDE and Postman for testing to database integration via Aiven’s MySQL service, each step is meticulously detailed. Explore the layered architecture, including the Presentation, Service, and DAO/Repository Layers, with clear instructions on endpoint creation, entity modeling, and CRUD operation implementation. This resource is a must-read for developers aiming to master API development using Spring Boot, concluding with expert tips on testing the API within Eclipse and validating it with Postman.
Server
Accepts request from client example: mobile, chrome
How Server works?
- Presentation Layer { Controllers } [ Accepts Request ]
- Service Layer { Checks for what s service to provide }
- Dao/Repository Layer { Share and add Data to database and Service layer }
- Databases { Store Data }
mobile, chrome → presentation layer ↔ service layer ↔ Dao/Repository Layer ↔ Database
API URL’s
Method API URL’s Operation
GET /users -> Get user
GET /users/{userId} -> Get single user
POST /user -> Add new user
PUT /user -> Update the user
DELETE /user/{userId} -> Delete the user
Requirements :
- IDE → Eclipse
- Postman
- Database → Aiven [ MySQL ]
spring initializr
- Spring web
- Spring data JPA
- Spring MySQL Driver
File System
- src/main/java
Packages
Controllers
Service - src/main/resources
Application Setup
Database connectivity - pom.xml
All dependencies are here
Procedure
Aiven Database Connection
Goto Aiven → register → services → MySQL → get User Data [ Free Services are provided here ]
Add database information with aiven data to application.properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://{Host}:{Port}/{Database_Name}
spring.datasource.username={UserName}
spring.datasource.password={Password}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Create interface for providing repository from database JpaRepository of database so we can make CRUD onto it
package com.springrest.springrest.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.springrest.springrest.entity.Users;
public interface UserDao extends JpaRepository<Users, Long>{
}
Create MyController class [ Main part to receive api request ] src.main.springrest.controller
Add Representational State Controller Mark
@RestController
public class MyController {
}
Create method and use getmapping, also checking if it’s working properly
@RestController
public class MyController {
@GetMapping("/test")
public String home() {
return "this is test page";
}
}
It’s working! Now Create model entity eg. Users inside src.main.springrest.springrest.entity
private long id;
private String name;
private int age;
// Generate Constructors using fields
// Generate Constructors using super
// Generate getters and setters for all
// Generate toString method for all
package com.springrest.springrest.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Users {
@Id
private long id;
private String name;
private int age;
public Users(long id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public Users() {
super();
// TODO Auto-generated constructor stub
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Users [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
Create controller mapping for all users in MyController
// get all users
@GetMapping("/users")
public List<Users> getUsers(){
}
Now, to get all users we need to have connector to database and here we use ‘services’
Create Services interface name UserService withing src.main.springrest.springrest.services
public interface UserServices {
public List<Users> getUser();
}
create UserImpl class where you will create main service and that will be connected to database repository and couple it with UserService using implements method
@Service
public class UserImpl implements UserServices {
@Autowired
private UserDao userDao;
public UserImpl() {
}
@Override
public List<Users> getUser() {
// TODO Auto-generated method stub
return userDao.findAll();
}
}
Now use this in MyController to pass data
@Autowired
private UserServices userServices;
// get all users
@GetMapping("/users")
public List<Users> getUsers(){
return this.userServices.getUser();
}
Do similar for others too
MyController
package com.springrest.springrest.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.springrest.springrest.entity.Users;
import com.springrest.springrest.services.UserServices;
@RestController
public class MyController {
@Autowired
private UserServices userServices;
// get all users
@GetMapping("/user")
public List<Users> getUsers(){
return this.userServices.getUser();
}
// single user
@GetMapping("/user/{userId}")
public Users getUsers(@PathVariable String userId) {
return this.userServices.getUser(Long.parseLong(userId));
}
// create user
@PostMapping(path="/add", consumes="application/json")
public Users addUser(@RequestBody Users user) {
return this.userServices.addUser(user);
}
// Update the users
@PutMapping("/update")
public Users updateUser(@RequestBody Users user) {
return this.userServices.updateUser(user);
}
// delete user
@DeleteMapping("/delete/{userId}")
public Users deleteUser(@PathVariable String userId) {
return this.userServices.deleteUser(Long.parseLong(userId));
}
}
UserService
package com.springrest.springrest.services;
import java.util.List;
import com.springrest.springrest.entity.Users;
public interface UserServices {
public List<Users> getUser();
public Users getUser(long userId);
public Users addUser(Users user);
public Users deleteUser(long userId);
public Users updateUser(Users user);
}
UserImpl
package com.springrest.springrest.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springrest.springrest.entity.Users;
import com.springrest.springrest.repository.UserDao;
@Service
public class UserImpl implements UserServices {
// List<Users> list;
@Autowired
private UserDao userDao;
public UserImpl() {
}
@Override
public List<Users> getUser() {
// TODO Auto-generated method stub
return userDao.findAll();
}
@Override
public Users getUser(long userId) {
// TODO Auto-generated method stub
return userDao.findById(userId).orElse(null);
}
@Override
public Users addUser(Users user) {
// TODO Auto-generated method stub
userDao.save(user);
return user;
}
@Override
public Users updateUser(Users user) {
// TODO Auto-generated method stub
userDao.save(user);
return user;
}
@Override
public Users deleteUser(long userId) {
// TODO Auto-generated method stub
Users user = userDao.findById(userId).orElse(null);
userDao.delete(user);
return user;
}
}
Now test it run on Eclipse and test it on postman