In this article, Under 10 Steps we shall look at how to create a simple RESTful api with spring boot by taking an example of USER.
Required Pre-requisites π£:
- Java installed on the machine π¨βπ».
- Postman to test the API's.
- Willing to learn π
Its time to jump into the code π
STEP 1: Create a base project from https://start.spring.io/. Give a project name and description. Add the 3 required dependencies: Spring Web, Spring Data JPA and MySQL driver.! Finally click on generate which will download a zip file. Extract and open in your preferred IDE like IntelliJ, eclipse or NetBeans.
In my case the application name is crud
STEP 2: Lets create some boilerplate by creating three folders in crud/src/main/java/com/example/crud/CrudApplication.java
which are 1. controller 2. model 3. repository 4. service. Typically your folder structure should look like below.
STEP 3: Create a Database and a users
table with user_id ( primary Key ), first_name and email
in your mysql
execut the following code which does the job for you in mysql terminal
CREATE TABLE `user_schema`.`users` (
`user_id` INT NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(45) NULL,
`email` VARCHAR(45) NULL,
UNIQUE INDEX `user_id_UNIQUE` (`user_id` ASC),
PRIMARY KEY (`user_id`));
and add the following code in crud/src/main/resources/application.properties
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/user_schema
#username and password of mysql
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
STEP 4: Let's do the magic by writing some code in these Folders. Create a file named User.java
in model
folder and add the following code.
package com.example.crud.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_id")
private Long id;
@Column(name="first_name")
private String firstName;
@Column(name="email")
private String email;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
STEP 5: Now create another file in repository
package named UserRepository.java
where it's class is extended from JPARepository
to enable query execution abilities like create()
, update()
, get()
and delete()
methods. finally add the following code
package com.example.crud.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.crud.model.User;
// @Repository tells the spring boot that it wrapped with User Table with sql execution queries.
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
STEP 6: Now Inside your service
folder create a file named UserService.java
. In this service layer we typically handle the business logic π€.
package com.example.crud.service;
import com.example.crud.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.crud.repository.UserRepository;
import java.util.List;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
public User createUser(User user){
return userRepository.save(user);
}
public List<User> getUsers(){
return userRepository.findAll();
}
public void deleteUser(Long userId){
userRepository.deleteById(userId);
}
public User updateUser(Long userId, User userDetails){
User user = userRepository.findById(userId).get();
user.setFirstName(userDetails.getFirstName());
user.setEmail(userDetails.getEmail());
return userRepository.save(user);
}
}
STEP 7: Now inside the controller
folder, create a file named UserController.java
. This is the first and foremost layer when a request hits the server. This is right place to do validate the params or authorising the API or adding some middleware validations. But right now we only focus on writing the basic structure of the controller.
Finally add the following code.
package com.example.crud.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.crud.model.User;
import com.example.crud.service.UserService;
// spring will understand that the methods in this class will follow rest convention
@RestController
@RequestMapping("/api")
public class UserController {
// spring will create a bean when we do a autowiring
@Autowired
UserService userService;
// invoking the spring-boot that this is end point /users
// to create USER
@RequestMapping(value="/users", method=RequestMethod.POST)
public User createUser(@RequestBody User usr) {
return userService.createUser(usr);
}
// to get all the list of Users
@RequestMapping(value="/users", method=RequestMethod.GET)
public List<User> readUsers() {
return userService.getUsers();
}
// to update the values of USER
@RequestMapping(value="/users/{userId}", method=RequestMethod.PUT)
public User readUsers(@PathVariable(value = "userId") Long id, @RequestBody User empDetails) {
return userService.updateUser(id, empDetails);
}
// to delete the record from the DB
@RequestMapping(value="/users/{userId}", method=RequestMethod.DELETE)
public void deleteUsers(@PathVariable(value = "userId") Long id) {
userService.deleteUser(id);
}
}
Finally your repository directory should look like:
Hurray !!!!! Thats it !! π€π€ Now you can start π the application on port number 8080 (of course the default port)
Step 8: Test π» your API using postman
Please find the postman collection link here: https://www.getpostman.com/collections/763c722809426a268aac
PS: You can find the github repository here https://github.com/SamalaSumanth0262/Spring-Boot-CRUD . Do follow me on https://github.com/SamalaSumanth0262 πββοΈ or https://twitter.com/sumanth0262 πββοΈ
Hey Peeps, This is my first blog π― on JAVA with spring boot. Please do leave any kind of improvements or suggestions. More than happy to hearπββοΈ.. Cheers !!! π»π»
Top comments (4)
Nice tutorial π
Great tutorial. π
Good work man, keep doing the sameπ―
Great work man, kudos to your efforts π
If possible can you add some creative use cases of this? Would be awesome π
Thanks once again, continue the great learning π