This article will introduce you to the Java Programming Language and REST APIs along with their key features. It will also explain the structure and working of REST API calls. Furthermore, the article will explain in detail, the steps required to create your own Java REST API using the Spring Boot platform. Read along to get a deeper understanding of Java REST APIs!

Prerequisites

  • IDE (Integrated Development Environment)
  • JDK (Java Development Kit) version 1.8+.
  • Maven 3.
  • Working knowledge of Java Programming Language.

What is Java REST API?

A Java REST API is a powerful way to build networked applications that follow the Representational State Transfer (REST) architectural style. REST APIs define how software applications communicate with each other, enabling seamless data exchange and interaction.

Why are Java REST APIs so popular?

  • Platform Agnostic: REST APIs can be accessed from various platforms (web, mobile, etc.), making them highly versatile.
  • Simplicity: REST principles promote simplicity in design and implementation.
  • Scalability: REST APIs are inherently scalable, making them suitable for high-traffic applications.
  • Flexibility: They offer great flexibility in terms of data formats (like JSON and XML) and communication protocols (like HTTP).
Unlock the power of your REST APIs with Hevo

Effortlessly extract valuable data from any REST API and seamlessly integrate it with your desired data warehouse or cloud storage.  Here’s how we simplify the process:

  1. Seamlessly pull data from REST API and over 150+ other sources with ease.
  2. Utilize drag-and-drop and custom Python script features to transform your data.
  3. Efficiently migrate data to a data warehouse, ensuring it’s ready for insightful analysis.

Experience the simplicity of data integration with Hevo and see how Hevo helped fuel Cure.Fit drive for accurate analytics and unified data.

Get Started with Hevo for Free

Understanding REST in Spring

The Spring framework supports two ways of creating RESTful services:

  • Using HTTP Message Converters
  • Using MVC with ModelAndView

The ModelAndView Approach is older and much better documented, but also more configuration-heavy and verbose. It tries to shoehorn the REST paradigm into the old model, which has its fair share of problems. The Spring team provided first-class REST support starting with Spring 3.0 to combat these issues.

The new approach, based on HttpMessageConverter and annotations, is much easier to implement and lightweight. Configuration is minimal, and it offers sensible defaults for what you can expect from a RESTful device.

Java Configuration in Spring

@Configuration
@EnableWebMvc
public class WebConfig{
   //
}

The new @EnableWebMvc annotation can execute a couple of useful things, specifically in the case of REST. For REST, it can detect the existence of JAXB 2 and Jackson on the classpath, and automatically registers and creates default XML and JSON converters. The functionality of the annotation is equivalent to the XML Version:

<mvc:annotation-driven />

Even though this is a shortcut that might be useful in various situations, it is far from perfect. When you need a more complex configuration, you can remove the annotation and extend WebMvcConfigurationSupport directly.

Steps to Create a Java REST API Using Spring Boost

Java REST API: API Working Diagram

The process requires you to design a model of network applications. This will generate the HTTP request to perform CRUD (Create, Read, Update and Delete)  operations on your data. It will return data as a result of your Java REST API call in JSON or XML format.

Step 1: Initialize the Spring Boot Project and Add Dependencies

Use the Spring Initializer to generate a Spring Boot project skeleton for you.

Now, add the following dependencies which will be required in the later steps.: 

  • Spring Web: It adds Spring MVC and Tomcat to your project. 
  • MySQL Driver: This is required for database functionality. 
  • Spring Data JPA: It is for Java Persistence API and Hibernate.
  • Spring Boot DevTools: They are required for project development. 

Click on generate to download a zip file that contains your generated project to your system.

Step 2: Build a Base Project Using Spring CLI

Open the console on your system and enter the following command:

spring init --build=maven -p=jar UserDemo

It will use Spring CLI to build your base project which you must import as a MAVEN project to your IDE. It may take some time. When the import is complete, you can view it in the Package Explorer section of your IDE.

Step 3: Set Up and Connect a Database

Now, you need to configure the Database using the Spring Data JPA (Java Persistence API). Enter the following code in the applications.properties file:

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

You can modify and switch the underlying database just by changing a few properties.

Step 4: Create a User Model for Java REST APIs

Once the Database connection is set and running, you can move on to the Domain Model. It is a collection of classes, that you will need to use later instruction. Hibernate ( A Java mapping tool) refers to these classes as Entities. Fetch each Entity from Hibernate, create a table to map its fields, and it will then act as a managed entity for your Database. The following code will carry out this mapping process:

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

Step 5: Create Repository Classes for Java REST APIs

Now you have to create a UserRepository that can execute CRUD operations on our User entities. Specify a Java REST API interface that can extend CrudRepository and unify it with @Repository using the following code:

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

The ​@Repository is a variation of the @Component annotation, which informs Spring that this component needs to be managed by the IoC container. ​The CrudRepository extension accepts the entity class, along with the identifier of the data type it should use to query.

CrudRepository declares folowing methods that form the basic CRUD functionality in a repository:

  • findAll()
  • findOne()
  • save()

Step 6: Create a Controller for Java REST APIs

This step implements the main logic of information processing using the components designed in the previous steps. 

Create a controller @RestController, which is just a combination of @Controller and @ResponseBody. This implies that instead of showing the pages, it will just respond with the data you gave it. The following code will set up your Controller:

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

    @Autowired
    private UserRepository userRepository;
        
    @GetMapping
    public List<User> findAllUsers() {
        // Implement
    }

    @GetMapping("/{S.no}")
    public ResponseEntity<User> findUserById(@PathVariable(value = "S.no") long S.no) {
       // Implement
    }

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

The @GetMapping and @PostMapping annotations specify the types of HTTP requests that this method can accept and handle.

  • Create findall() functionality:
@GetMapping
public List<User> findAllUsers() {
    return userRepository.findAll();
}
  • Create an Endpoint to get the user id:
@GetMapping("/{S.no}")
public ResponseEntity<User> findUserById(@PathVariable(value = "S.no") long S.no) {
    Optional<User> user = userRepository.findById(S.no);

    if(user.isPresent()) {
        return ResponseEntity.ok().body(user.get());
    } else {
        return ResponseEntity.notFound().build();
    }
}
  • Create an Endpoint to save a user:
@PostMapping
public User saveUser(@Validated @RequestBody User user) {
    return userRepository.save(user);

Step 7: Compile and Execute the Code for Java REST APIs

You can directly run the application using the following command on the command line from your base project folder:

./mvnw spring-boot:run 

Your code is working correctly if your screen starts printing such log entries:

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)

Your application is up and successfully running on http://localhost:8080/.

Step 8: Test the Java REST APIs

To test the GET requests connect to the http://localhost:8080/api/user endpoint with the following GET request:

$ curl http://localhost:8080/api/user

Your screen will show the following JSON response:

 {
      "S.no": 1,
      "name":"Prince"
   },
   {
      "S.no": 2,
      "name":"Rahul"
   },
   {
      "S.no":3,
      "name": “Amit"
   }
]

Now, send an HTTP POST request as a user to the database created in previous steps:

$ curl --location --request POST 'http://localhost:8080/api/user' 
--header 'Content-Type: application/json' 
--data-raw '{ "S.no": 2, "name": "Rahul" }'

(Note: The fields in the JSON payload request must match the field names in your DB/model.)

The Java REST API will give 200 as a response with the following displayed on your screen:

{
    "S.no": 2,
    "name": "Rahul"
}

That’s it! You have created and tested your own Java REST API using Springer.

Solve your data replication problems with Hevo’s reliable, no-code, automated pipelines with 150+ connectors.
Get your free trial right away!

Advantages of using Spring Boot

Spring Boot is one of the Java frameworks built on top of the Spring, leveraged for developing web applications. It lets you create REST APIs with minimal configurations. A few key benefits of using Spring Boot are as follows:

  • The Embedded Tomcat server can run Spring Boot applications with ease.
  • No requirement for complex XML configurations.
  • An auto-configuration feature by Spring Boot that configures your application automatically for certain dependencies. If the dependency is available in your classpath, Spring Boot will auto-create the components for it. Beans in Spring are objects that are managed and instantiated by Spring through Spring IoC containers. This means that you don’t have to generate or configure the Beans since Spring Boot will do that for you.

Best Practices for Building Effective REST APIs

  • Uniform Interface: Use consistent and predictable request/response formats.
  • Client-Server Architecture: Separate user interface concerns from data storage for better maintainability.
  • Statelessness: Each request should be independent and contain all the necessary information.
  • Cacheability: Define cacheability for responses to improve performance and reduce server load.
  • Layered System: Implement a layered architecture for better organization and maintainability.

Conclusion

Java REST APIs have become a cornerstone of modern application development, offering a powerful and flexible approach to building networked applications. By adhering to REST principles and leveraging frameworks like JAX-RS and Spring Boot, developers can create robust, scalable, and maintainable APIs that power a wide range of applications, from mobile apps and web services to enterprise-level systems.

As the demand for interconnected applications continues to grow, mastering Java REST API development is crucial. If you’re looking to streamline your data integration and leverage the power of your REST APIs, consider Hevo. Hevo Data simplifies data integration by connecting to numerous sources, including APIs, and seamlessly loading data into your desired destinations. Sign up for a free trial and learn more.

FAQs

1. What is the REST API in Java?

A REST API in Java refers to the implementation of a Representational State Transfer (REST) API using the Java programming language. It allows Java applications to interact with other applications or services over the HTTP protocol by exposing endpoints (URLs) for performing CRUD operations (Create, Read, Update, Delete) on resources. Common frameworks used to build REST APIs in Java include Spring Boot, JAX-RS, and Java EE.

2. What are the four types of REST APIs?

GET: Retrieves data from the server (used for reading).
POST: Sends data to the server to create a new resource.
PUT: Updates an existing resource on the server.
DELETE: Deletes a resource from the server.

3. Is REST API frontend or backend?

A REST API is typically part of the backend. It serves as the intermediary that allows the frontend (e.g., a web or mobile app) to interact with a database or other backend services. The frontend makes HTTP requests to the REST API, and the API processes those requests and returns data in a format like JSON or XML.

Abhinav Chola
Research Analyst, Hevo Data

Abhinav Chola, a data science enthusiast, is dedicated to empowering data practitioners. After completing his Master’s degree in Computer Science from NITJ, he joined Hevo as a Research Analyst and works towards solving real-world challenges in data integration and infrastructure. His research skills and ability to explain complex technical concepts allow him to analyze complex data sets, identify trends, and translate his insights into clear and engaging articles.