Most of the applications you use these days follow the Client-Server Architecture. The Application itself is considered the Client or the Front-End part, and it needs to talk to a Server or the Back-End to load or pull the data. This communication is established with the help of the HTTP protocol, and yes, it’s the same protocol that powers our Web.

The Client can directly call the HTTP Services exposed on a Server by sending HTTP requests. This is where a REST API like Spring Boot REST API can help you retrieve information from another system. This article will guide you on how to build a Spring Boot REST API in Java. Upon completion, you will understand and use REST API Spring Boot step by step and spring boot rest api example.

Building a Spring Boot REST API in Java

Follow the below-mentioned steps to build a Spring Boot REST API using Java.

Do you want to use REST API to replicate your data? Solve your data replication problems with Hevo’s reliable, no-code, automated pipelines with 150+ connectors.
Get your free trial right away!

Step 1: Initializing a Spring Boot Project

To start with Spring Boot REST API, you first need to initialize the Spring Boot Project. You can easily initialize a new Spring Boot Project with Spring Initializr.

From your Web Browser, go to start.spring.io. Choose Maven as your Build Tool and Language as Java. Select the specific version of Spring Boot you want to go ahead with.

Spring Boot REST API: Spring Initialize | Hevo Data
Image Source: Stackabuse

You can go ahead and add a few dependencies to be used in this project.

  • Spring Data JPA Java Persistence API and Hibernate.
  • Spring Web To include Spring MVC and embed Tomcat into your project.
  • Spring Boot DevTools – Development Tools.
  • MySQL Driver – JDBC Driver (any DB you want to use).

Once you’re done with the configuration, click on “Generate”. A ZIP file will then be downloaded. Once the download is finished, you can now import your project files as a Maven Project into your IDE (such as Eclipse) or a text editor of choice.

Step 2: Connecting Spring Boot to the Database

Next, you need to set up the Database, and you can do it easily with Spring Data JPA.

Add some elementary information in your application.properties file to set up the connection to your preferred Database. Add your JDBC connection URL, provide a username and password for authentication, and set the ddl-auto property to update.

Hibernate has different dialects for different Databases. Hibernate automatically sets the dialect for different Databases, but it’s a good practice to specify it explicitly.

spring.datasource.url = jdbc:mysql://localhost:3306/user
spring.datasource.username = user
spring.datasource.password = user
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Step 3: Creating a User Model

The next step is to create a Domain Model. They are also called Entities and are annotated by @Entity.

Create a simple User entity by annotating the class with @Entity. Use @Table annotation to specify the name for your Table. @Id annotation is used to annotate a field as the id of an entity. Further, set it as a @GeneratedValue and set the GenerationType to AUTO.

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String name;
}

Now, this class (entity) is registered with Hibernate.

Step 4: Creating Repository Classes

To perform CRUD (Create, Read, Update, and Delete) operations on the User entities, you’ll need to have a UserRepository. To do this, you’ll have to use the CrudRepository extension and annotate the interface with @Repository.

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

Step 5: Creating a Controller

You’ve now reached the Business Layer, where you can implement the actual business logic of processing information.

@RestController is a combination of @Controller and @ResponseBody.Create a UserController as shown below.

@RestController
@RequestMapping("/api/user")
public class UserController {
 
    @Autowired
    private UserRepository userRepository;
        
    @GetMapping
    public List<User> findAllUsers() {
        // Implement
    }
 
    @GetMapping("/{id}")
    public ResponseEntity<User> findUserById(@PathVariable(value = "id") long id) {
       // Implement
    }
 
    @PostMapping
    public User saveUser(@Validated @RequestBody User user) {
        // Implement
    }
}

You’ve to @Autowired your UserRepository for dependency injection. To specify the type of HTTP requests accepted, use the @GetMapping and @PostMapping annotations.

Let’s implement the findAll() endpoint. It calls the userRepository to findAll() users and returns the desired response.

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

To get each user by their id, let’s implement another endpoint.

@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();
    }
}

If the user.isPresent(), a 200 OK HTTP response is returned, else, a ResponseEntity.notFound() is returned.

Now, let’s create an endpoint to save users. The save() method saves a new user if it isn’t already existing, else it throws an exception.

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

The @Validated annotation is used to enforce basic validity for the data provided about the user. The @RequestBody annotation is used to map the body of the POST request sent to the endpoint to the User instance you’d like to save.

Step 6: Compile, Build and Run

You can change the port of Spring Boot from your application.properties file.

server.port = 9090

8080 is the default port that Spring Boot runs in.

It’s time to run the Spring Boot REST API you’ve created. To run the application, directly execute ./mvnw spring-boot:run on the command line from your base project folder where pom.xml is located.

If your application has successfully run, you’ll be able to 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 started on port(s): 8080 (http) with context path ''
2020-11-05 13:27:05.121  INFO 21796 --- [  restartedMain] com.howto.DemoUser.DemoUserApplication   : Started DemoUserApplication in 1.765 seconds (JVM running for 2.236)

Step 7: Testing the Spring Boot REST APIs

Your Spring Boot REST API is now up and running on http://localhost:8080/.

Use your browser, curl, or Postman to test the endpoints.

Steps for testing using curl

To send an HTTP GET request, go to http://localhost:8080/api/user from your browser and it will display a JSON response as shown.

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

Now, send an HTTP POST request to add specific users to your Database.

$ curl --location --request POST 'http://localhost:8080/api/user' 
--header 'Content-Type: application/json' 
--data-raw '{ "id": 4, "name": "Jason" }'

The API will return a 200 OK HTTP response with the response body of the persisted user.

{
    "id": 4,
    "name": "Jason"
}

Testing using Postman

Create a workspace in Postman to coordinate with your team for projects. 

  • Select Workspace under dropdown -> click on New workspace in Postman app.
Spring Boot REST API: Create workspace
  • Type in the name of your workspace. You can decide who all can see your workspace by choosing under Visibility section -> Select the Create Workspace button.
Spring Boot REST API: last step in creating workspace
  • Click on Create new Collection icon in the left panel to create a collection.
Spring Boot REST API: create new collection
  • Select  Edit -> Type in your “Employee collection”.
Spring Boot REST API: type in employee collection
  • Then, you can create and test requests in your collection for each of the REST APIs created in your Spring Boot application.
  • Select View more actions in the left panel for the collection you created -> Click on Add request.
Spring Boot REST API: add request
Spring Boot REST API: employee collection drop down
  • Provide a request name “Create Employee”. The following diagram shows that:
Spring Boot REST API: create employee
  • Make the HTTP method as POST.
Spring Boot REST API: make HTTP method
Spring Boot REST API: Enter request URL
  • Replace the 8080 in the URL when your app is running in another port.
  • To send a request body to this request URL endpoint, Go to the Body tab select the raw checkbox for the request body format as JSON.
Spring Boot REST API: select checkbox
  • Type in the following data you want to add to DB in the textbox:

{ “firstName”:”Nida”, “lastName”:”Khan”, “emailId”:”example1@gmail.com” }

  • Select Save -> Send. The output will look like:

{ “id”: 1, “firstName”: “Nida”, “lastName”: “Khan”, “emailId”: “example1@gmail.com” }

  • Run the following query in MySQL Workbench to verify that there is a new row having employee details associated with  emp_id=1. SELECT * FROM employee;
Spring Boot REST API: run query
Spring Boot REST API: send
  • For an employee with a selected ID, create a PUT request to UPDATE it. In the Enter Request URL -> Copy and paste “http://localhost:8080/api/employees/1”. Type in the following details in the raw JSON body -> Press Send:

{ “firstName”: “Nida”, “lastName”: “K”, “emailId”: “example2@gmail.com” }

Spring Boot REST API: press send
  • Create a DELETE request to  DELETE an employee record. Enter “http://localhost:8080/api/employees/1” in the Enter Request URL field. Press Send without entering anything in the Body.
Spring Boot REST API: send without body

That’s it, you have now successfully tested your Spring Boot REST API. The following are the pros of using Sprint Boot for REST APIs.

Advantages of using Spring Boot for REST APIs

  • You won’t need complex XML configurations.
  • You can run Spring Boot applications using an embedded Tomcat server.
  • You can configure your application automatically for certain dependencies using Spring Boot’s auto-configuration feature. Whenever dependency is available in your classpath, Spring Boot creates the beans for it (Beans means the objects instantiated and managed by Spring through Spring IoC containers) automatically.

Conclusion

API is a bigger umbrella, and REST API is a unique type of API prevalent among cloud applications. REST APIs are all about communication. This article introduced you to REST APIs and further provided you with a detailed guide on how to build and use Spring Boot REST APIs in Java.

Extracting complex data from a diverse set of free data sources like Spring Boot REST APIs can be a challenging task and this is where Hevo saves the day!

Hevo is the only real-time ELT No-code Data Pipeline platform that cost-effectively automates data pipelines that are flexible to your needs. With integration with 150+ Data Sources (40+ free sources), we help you not only export data from sources & load data to the destinations but also transform & enrich your data, & make it analysis-ready.

visit our website to explore hevo

Give Hevo Data a try and sign up for a 14-day free trial today. Hevo offers plans & pricing for different use cases and business needs, check them out!

Share your experience of working with Spring Boot REST API in the comments section below.

Reference: Create REST APIS with SPRING BOOT

Raj Verma
Business Analyst, Hevo Data

Raj is a skilled data analyst with a strong passion for data analysis and architecture, having a flair for writing technical content as well. With extensive experience in handling marketing data, Raj has adeptly navigated abstract business problems to derive actionable insights that drive significant results.

No-code Data Pipeline For Your Data Warehouse