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 Programming Language?

Java REST API: Java Logo

Java is a general-purpose object-oriented programming language that is widely used in the Software Development process. With its multithreaded functionality, you can write programs that can multitask. This design feature allows developers to create smooth and interactive applications.

Also, since Java byte code is directly translated into the native machine language, the development process is faster and more analytical as incremental and lightweight linking is required.  This programming language works best for distributed systems and uses Just-in-Time compilers to enhance performance.

Key Features of Java Programming Language

The following features give Java an edge over other Programming Languages:

  • Object-Oriented: Java Programming Language treats everything as an object. It can easily map real-world scenarios into code by treating individual entities as objects. 
  • Platform Independent: Unlike programming languages ​​like C and C ++, Java is not compiled in a platform-specific machine. It produces a platform-independent Byte Code that is distributed over the internet and is interpreted by the Java Virtual Machine (JVM) installed on any system. 
  • Security: With the security feature of Java Programming Language, it allows you to develop tamper-proof and virus-free systems. Also, it uses Public-key cryptography-based authentication techniques to keep your code and data safe.
  • Portable: Java is an architecture-independent Programming Language. So it is easy to port a code written in Java Programming Language to different processors.
  • Robust: Java is a Programming Language that strives to eliminate error-prone instances using compile-time error checking and runtime checking.

What are REST APIs?

Java REST API: REST API Logo

REST APIs allow multiple software applications to communicate and share data. It involves organizing your code in such a way, that it is accessible from various applications.

Your REST API program is a server code that provides access to your data and authenticates the users who are sending data requests. The other applications will use this REST API to interact with your data. Any REST API must contain the following components:

  • Endpoints: A REST API’s Endpoint is a single URL that represents an object or a collection of data objects grouped. The address to which the API sends a request and from where the response emanates is known as an endpoint. Every API request has an endpoint associated with it. 
  • Headers: REST headers contain the metadata that describes each REST API request. A REST header represents the format of the request, the format of the response, and updates regarding the status of the request. 
  • Client-Server Architecture: REST APIs work on a client-server architecture, in which the server and the client act independently when managing a request-response operation. The interface between them however remains constant throughout the interaction. The server contains the information and transfers it to the user as per the client’s request. 

Working of REST APIs

A REST API requires a host URL that acts as the primary address for your interactions. REST APIs also need a set of endpoints, which are unique addresses within-host URLs responsible for its functionality. Moreover, it is a good practice to document the endpoints, return value, data types, and other essentials of a REST API. 

The below diagram is a high-level representation of the required organization of your code to create a REST API. You may have one or more databases that contain data that other applications might need. So, they will use the REST API that uses SQL and JDBC to interact with the database. REST APIs enable you to centralize all your basic logic in one place instead of rewriting it every time you want to create a new app as shown by the below image. 

Java REST API: Structure of REST API

Now, APIs are designed to return the required data whenever a user calls them. However, when you use REST APIS, it not only returns the requested data but also presents it in a well-structured form for representation.

A REST API utilizes a client-server architecture that allows different applications to communicate. The client software makes a call to the server application using a REST API. The Server application sends the requested data in a structured form organized using key parameters over the HTTP protocol.

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
Image Source

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.

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.

Conclusion

This blog introduced Java Programming Language and REST APIS and explained their key features. It further provided the steps that you can follow to create your own Java REST API solution.

Furthermore, it also discussed the structure and working of RESt APIs. In recent decades, REST APIs have dominated the development process, especially among Android Developers.

Share your understanding of the Java Rest APIs in the comments below!

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.

No Code Data Pipeline For Your Data Warehouse