How to Create REST API in Java using Spring Framework

In this article, you will learn how to create Rest API in Java. But before we start to learn about it we need to understand what is Rest Api.

What is REST API?

REST APIs are rules, routines, commands, and protocols or the glue that integrates the individual microservices so that they function as a single application. REST stands for REpresentational State Transfer. It is a software architectural style that uses a subset of HTTP. It is commonly used to create interactive applications that use web services. The major advantage of using REST is that it makes it easier for systems to communicate with each other.

image10.png

Here we will be creating a REST API using Spring Framework. The major reasons for using Spring Framework for creating API’s are:

  • HTTP Support: In Spring, the controller can handle all HTTP methods like GET, POST, PUT, PATCH, and DELETE.
  • Bypassing View-Based Rendering: Annotations are used in spring MVC to bypass view-based rendering.
  • REST Annotations: In Spring 4.0 @RestController annotation was added to make the development of REST APIs much easier.
  • Support to extract data from URL: Rest pass resource identifies data in URI itself like subjects/101.
  • JSON, HTML, and XML formatting support: Another key aspect of Restful Web Services is the representation of data in the form of JSON XML and HTML. Spring provides a view resolver to render data in the form of JSON XML and HTML.
  • Request body and response body annotations: Response body annotation is used to convert the response to the format the client wants. Request body annotation is used to convert inbound HTTP data into java objects.
  • REST template to consume REST API: The spring framework also provides a template class RestTemplate which is similar to JdbcTemplate which can consume Rest resources.

The major requirement for creating a Rest API are:

  • A text editor or IDE.
  • JDK 1.8 or later.
  • Gradle 4+ for Maven 3.2+.
  • You can also import the code directly into the IDE:
  • Spring tool suite(STS)
  • Intellij IDEA.

Now after understanding the Rest API we will start with how to create them. For that we have to follow the following steps:

1.Initialize a spring boot project using a spring initializer. It automatically creates a skeleton spring boot project for you.

image2.png

A few dependencies like Spring web, spring data JPA, Spring boot dev tools, And my SQL driver have to be added which will be used In our project. After this press generates and a zip file containing the generated code will be downloaded.

2.Connecting spring boot to the database:Before starting with the application, we first have to create a database. This can be done using spring data which helps in setting up connections using just a couple of parameters. In the application.properties file some additional information needs to be added.

spring.datasource.url = jdbc:my;q1://loca1host:3306/user 
spring.datasource.username = user 
spring.datasource.password = user 
spring.jpa.hibernate.cdl-auto = update 
spring.jpa.p-operties.hibernate.dialect = org.hibernate.dial!ct.MySQLEDialect 

3.Create a user model: First, let's create a simple User entity. We'll annotate the class with @Entity and the optional @Table annotation to specify the name for the table.

@Entity 
@Table(name = "user") 
public class User { 

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
private long id; 
private String name; 

// Constructor, getters and setters
}

4.Creating repository classes: We'll want to have a UserRepository to perform CRUD operations on our User entities. To do this, we'll specify an interface that extends CrudRepository, and annotate it with @Repository.

@Repository 
public interface UserRepository extends CrudRepository<User, Long> {} 

CrudRepository declares methods like findAll(), findOne(), and save() which constitute the basic CRUD functionality of a repository. You can use this UserRepository as-is, to perform CRUD operations on User entities now, with no further setup required.

5.Creating a controller: Let's create a controller, mark it as a @RestController, as we're creating a REST API, and add a @RequestMapping to it. @RestController is just a combination of @Controller and @ResponseBody, which means that instead of rendering pages, it'll just respond with the data we've given it. This is natural for REST APIs - returning information once an API endpoint has been hit.

@RestController 
@RequestMapping("/api/user") 
public class UserController { 

@Autowired 
private UserRepository userRepository; 

@GetMapping 
public List<User> findAllUsers() {
//Implement

 } 

@GetMapping("/{id}") 
public ResponseEntity<User> findUser8yId(pathVariable(value = "id") long id) { 
//Implement
} 

@PostMapping 
public User saveUser(@Validated @RequestBody User user) { 
//Implement
} 
} 

We've @Autowired our UserRepository. It's used for dependency injection, as the repository class is a dependency here. We've also used the @GetMapping and @PostMapping annotations to specify which types of HTTP requests our methods are accepting and handling. These are derived variants of the @RequestMapping annotation, with a method = RequestMethod.METHOD set for the respective types.
Let's start off with the implementation for the findAll() endpoint:

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

Next, let's implement the endpoint to get each user by their id:

@GetMapping("/{id}") 

public ResponseEntity<User> findUserById(@PathVariable(value = "id") long id) { 
Optional<User> user = userRepository.findById(id); 

if(user.isPresent()) { 
      return ResponseEntity.ok().body(user.get());
 } else { 
return ResponseEntity.notFound().build(); 
}

Finally, let's make an endpoint to save users:

@postMapping 
public User saveUser(@Validated pequest8ody User user) { 
    return userRepository.save(user); 
}

6.Compile build and run: The default port that Spring Boot runs in is 8080. You will know when your application has successfully run if you see these audit logs at the end of your command line:

2020-11-05 13:27:05.073 INFO 21796 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2020-11-05 13:27:05.108 INFO 21796 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat star ted on port(s): 8080 (http) with context path " 2020-11-05 13:27:05.121 INFO 21796 --- [ restartedMain] com.howto.DemoUser.DemoUserApplication : Started Dem oUserApplication in 1.765 seconds (JVM running for 2.236) 

7.Testing the API: Now that your application is up and running on http://localhost:8080/, we can now test the endpoints to see if they work. In your browser address bar, visit http://localhost:8080/api/user, and your browser will display a JSON response:

[
{
     "id": 1, 
      "name":"John" 
},
{
      "id": 2, 
       "name":"Jane"
},
{ 
       "id": 3, 
       "name": "Juan" 
}
]

Conclusion:

One of the most frequently asked Questions in Java Interview includes how to create Rest API in java. There you have it. You've successfully built your very own Spring Boot REST API! Check out more questions here.

Coin Marketplace

STEEM 0.20
TRX 0.13
JST 0.029
BTC 65845.60
ETH 3304.70
USDT 1.00
SBD 2.69