Working with Java REST APIs: 3 Comprehensive Aspects

on API, Java, REST API, Tutorials, Uncategorized, Web APIs • April 11th, 2022 • Write for Hevo

Developers often require data stored in another software tool or application. Now, the process of understanding the software’s code to extract valuable information is a time-consuming and hectic task. API (Application Programming Interface) calls were devised to overcome this situation. APIs are a set of protocols (rules) that govern the interaction between software applications. They allow Developers to skip the hassle of exploring the source code of certain third-party software. Instead, users can just invoke an API call to access the data and resources of another software seamlessly.

When the API calls implement HTTP (Hypertext Transfer Protocol) protocol to communicate and use JSON (JavaScript Object Notation) file format to structure the data, they are called REST (Representational State Transfer) APIs. They are often used as a public tool for third-party software like mobile applications to provide required services. The code for REST APIs can be written in multiple languages but Java Programming Language due to its “write once run anywhere” quality is preferred for creating these APIs. 

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!

Table of Contents

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

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.

To learn more about Java Programming Language, visit here.

What are REST APIs?

Java REST API: REST API Logo
Image Source

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. 

Key Features of REST APIs

The following features make REST APIs unique:

  • Stateless: REST APIs work on a stateless design. This implies that whenever a client and a server communicate, they require extra information to complete the request. Moreover, it means that there is no session state, and if authentication is required, then the client must authenticate the process each time it makes a request. 
  • Cache-based: REST APIs can also be cached, which means that the client, server, and any connected middleware are all able to cache resources for better performance. 
  • Layered Architecture: REST APIs use a layered architecture in which a layer has a specific function and the output of one layer serves as the input of another. While the layers have their responsibilities, they must also interact with each other and maintain a hierarchy within the REST API architecture. 
  • Uniform Interface: REST APIs use a uniform interface to allow the client to speak to the server in a specific language. This allows the application to evolve independently without any of its services, models, or other functions in conjunction with the REST API.

To learn more about REST APIs, visit here.

Simplify your Data Analysis with Hevo’s No-code Data Pipeline

Hevo Data, a No-code Data Pipeline helps to Load Data from any data source such as Databases, SaaS applications, Cloud Storage, SDK,s, its and Streaming Services and simplifies the ETL process. It supports 100+ data sources and loads the data onto the desired Data Warehouse, enriches the data, and transforms it into an analysis-ready form without writing a single line of code.

Get Started with Hevo for Free

Check out why Hevo is the Best:

  • Secure: Hevo has a fault-tolerant architecture that ensures that the data is handled in a secure, consistent manner with zero data loss.
  • Schema Management: Hevo takes away the tedious task of schema management & automatically detects the schema of incoming data and maps it to the destination schema.
  • Minimal Learning: Hevo, with its simple and interactive UI, is extremely simple for new customers to work on and perform operations.
  • Hevo Is Built To Scale: As the number of sources and the volume of your data grows, Hevo scales horizontally, handling millions of records per minute with very little latency.
  • Incremental Data Load: Hevo allows the transfer of data that has been modified in real-time. This ensures efficient utilization of bandwidth on both ends.
  • Live Support: The Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
  • Live Monitoring: Hevo allows you to monitor the data flow and check where your data is at a particular point in time.
Sign up here for a 14-Day Free Trial!

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

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.

Visit our Website to Explore Hevo

You may want to go one step further and perform an analysis of the JSON data collected by your Java REST API. This will require you to transfer data from your system to a Data Warehouse using various complex ETL processes. Hevo Data will automate your data transfer process, hence allowing you to focus on other aspects of your business like Analytics, Customer Management, etc. This platform allows you to transfer data from 100+ multiple sources to Cloud-based Data Warehouses like Snowflake, Google BigQuery, Amazon Redshift, etc. It will provide you with a hassle-free experience and make your work life much easier.

Want to take Hevo for a spin? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand.

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

No Code Data Pipeline For Your Data Warehouse