Sunday, April 30, 2023

How to create RESTful Web Services in Java using Spring Boot? Example Tutorial

Hello guys, if you are looking for a complete tutorial to create REST API on Spring Boot then you have come to the right place. In the past, I have shared the best RESTful Web Services courses and best Spring Boot courses and in this article, I am going to show you how to create RESTful web services using Spring Boot step by step. After going through this tutorial you will be able to create your own REST endpoints and RESTful application using Spring Boot and Spring Framework and Java programming language. How to make Spring boot REST API? is a common question that everyone has who is new to Spring boot application development. 

Most of the programs are now rely on REST API and need to have proper knowledge in developing REST APIs in order to communicate with the frontend application. REST stands for REpresentational State Transfer, a standardized approach to building web services.

A REST API is an application programming interface that allows two programs to interact through HTTP, similar to how servers communicate with browsers. 

Let's say you have a student management system, So adding students to the application is done in two different ways with the frontend and backend of the programming with the use of REST API to communicate with them.




Spring Boot + RESTful Web Service Example Tutorial

In this tutorial, we will discuss how to create Spring boot REST APIs by creating an example project.

how to create RESTful Web Services in Java using Spring Boot? Example Tutorial


First, we create a project using the spring initializer and add the following dependencies before creating the project. 
  •          Web
  •          MySQL
  •          JPA
  •          DevTools
Spring Boot + RESTful Web Service Example
Spring initializer used to create the project.




Step by Step guide to create RESTful Web Services in Java using Spring Boot.


Once you create the project, here are the steps you can follow to create a RESTFul Web service in Java using Spring framework and Spring Boot. 

1. Make the database configuration.

In the application that you created using the Spring initialization, you need to configure the database username and password in the application.properties file.

server.port=8081
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.hibernate.ddl-auto=create-drop
spring.datasource.url=jdbc:mysql://localhost:3306/studentdb?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

#Debug
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

#Context path and health check
server.servlet.context-path=/zenopos
management.endpoints.web.exposure.include=health




Then create the Student class with the following properties.
 
@Entity
@Table(name = "student")
@EntityListeners(AuditingEntityListener.class)
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
    @Column(name = "first_name", nullable = false)
private String firstName;
    @Column(name = "last_name", nullable = false)
private String lastName;
    @Column(name = "email", nullable = false)
private String email;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email= email;
}
}



Then create the Student JPA data repository layer as follow.
@Repository
public interface StudentRepository extends 
                   JpaRepository<Student, String> {
   
}
Then create the Student rest controller and map API requests.

@RestController
@RequestMapping("/api")
public class StudentController{
@Autowired
private StudentRepository studentRepository;

@GetMapping("/students")
public List<Student> getAllStudents();

@GetMapping("/students/{id}")
public ResponseEntity<Student> getStudentById(@PathVariable(value="id") Long studentId){
Student student = studentRepository.findById(studentId);
if(student == null){
return new ResponseEntity(errors, HttpStatus.SERVICE_UNAVAILABLE);
}
return new ResponseEntity(student, HttpStatus.OK);
}

@PostMapping("/students")
public Student addStudent(@Valid @RequestBody Student student){
return studentRepository.save(student);
}

}

So in order to test the created APIs, we can create unit tests as below.

This helps to test the system which get the expected output.


@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class StudentApplicationTests {

@Autowired
private TestRestTemplate restTemplate;

@LocalServerPort
private int port;

private String getRootUrl() {
return "http://localhost:" + port;
}

@Test
public void contextLoads() {
}

@Test
public void getAllStudentTest() {
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity = new HttpEntity<String>(null, headers);

ResponseEntity<String> response = restTemplate.exchange(getRootUrl() + "/students",
HttpMethod.GET, entity, String.class);

Assert.assertNotNull(response.getBody());
}

@Test
public void GetStudentByIdTest() {
Student student = restTemplate.getForObject(getRootUrl() + "/students/1", Student.class);
System.out.println(student.getFirstName());
Assert.assertNotNull(student);
}

@Test
public void CreateStudentStudent() {
Student student = new Student();
student.setEmail("studnet@gmail.com");
student.setFirstName("studentfirstname1");
student.setLastName("studentlastname1");

ResponseEntity<Student> postResponse = restTemplate.postForEntity(getRootUrl() + "/student", student, Student.class);
Assert.assertNotNull(postResponse);
Assert.assertNotNull(postResponse.getBody());
}
}

run the application with the following command or run this in your java IDE. 
  • mvn package
  • java -jar target/studentproject-1.0.0.jar
So this application will run on the port 8081. In this tutorial we discussed about how to make
Spring boot REST API with a simple example using Student class.



So let's have a problem which might be having on creating a spring boot REST API.

You want to make a simple java application and  use CRUDREPOSITORY and my with your . So you have the following class which is configured.

@RestController
@Transactional
@ExposesResourceFor(Person.class)
@RequestMapping("/person")
public class PersonController {

@RequestMapping(value="/person", method=RequestMethod.GET)
public String person(@RequestParam(value="id", defaultValue="1") int id) {
return "hola"+id;
}

}

this:
@RepositoryRestResource
public interface IClientRepository extends CrudRepository<Client, Long> {
}

The problem is that the CRUD works well, but can´t call localhost:8080/person because it gives a 404 error.
How to make RESTful Web Services using Spring Boot and Java - Example Tutorial

To answer this,

By default, Spring Data REST serves up REST resources at the root URI, "/". There are multiple ways to change the base path. With Spring Boot 1.2+, add below to application.properties:

spring.data.rest.basePath=/api

In this case: spring.data.rest.basePath=/person/person, assuming there is no override for server.contextPath in application.properties.

That's all about how to create RESTful Web Services in Java using Spring Boot. So in this tutorial, we have discussed how to make spring boot rest API with some examples. I hope this will help you to understand how the things are going with spring boot and create the first application with the REST API. So see you in the next tutorial.

   Other Java and Spring Tutorial you may like
  • How Spring MVC works internally? (answer)
  • Difference between @Component@Service, and @Controller in Spring (answer)
  • Spring Data JPA Repository (JpaReposistory example)
  • Spring Data JPA @Query Example (query example)
  • What is @Conditional annotation in Spring? (conditional example)
  • 20+ Spring MVC Interview Questions for Programmers (answer)
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • 13 Spring Boot Actuator Interview questions (boot questions)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • Difference between @RequestParam and @PathVariable in Spring (answer)
  • Top 7  Courses to learn Microservices in Java (courses)
  • Difference between @Autowired and @Inject in Spring? (answer)
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • How to create your first Spring MVC appliation (tutorial)
  • How to use @Bean in Spring framework (Example)
  • 5 Courses to Learn Spring Security for Java programmers (courses)
  • Top 5 Spring Boot Annotations Java Developers should know (read)
  • Spring Boot + Reactjs example (example)
  • 5 Spring Cloud annotations Java programmer should learn (cloud)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • How to upload and download file using Spring Boot (Example)
  • 10 Spring MVC annotations Java developer should know (annotations)
  • How to update an entity using Spring Data JPA? (example)
  • @SpringBootApplication vs. @EnableAutoConfiguration? (answer)

Thanks for reading this article so far. If you find this Spring Boot and REST API Example Tutorial  then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. - If you are a beginner and want to learn the Framework from scratch and look for some of the best online resources, you can also check out these best Spring MVC courses for beginners. This list contains free Udemy and Pluralsight courses to learn Spring MVC from scratch.     

No comments:

Post a Comment