How to build api in java

How to Build a Spring Boot REST API with Java?

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. In this blog, we’ll discuss one such integration using Spring Boot REST API.

The Client can directly call the HTTP Services exposed on a Server by sending HTTP requests. This is where REST APIs come into the picture. REST is basically a convention for building these HTTP Web Services. 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. Spring Boot is an open-source Java-based tool used to create Web Applications and Microservices with ease. Upon completion, you’ll be in a better place to understand and use Spring Boot REST APIs easily. Let’s discuss this in detail.

Table of Contents

What is REST API?

An Application Programming Interface (API) establishes a connection between computers or between computer programs (applications) by providing readily available codes and information pipelines. It is a type of software interface that acts as a mediator among other pieces of software to streamline the interaction with one other.

Owing to diverse application architectures, different types of APIs such as Program, Local, Web, or REST APIs assist developers in building robust digital solutions.

Representational State Transfer, also known as REST, is basically a standardized Software Architecture Style, or in simple words, a specific type of API used by the industry to establish a connection between Client and Server. REST API is built to guide the development and design of the World Wide Web’s architecture.

REST APIs provide a flexible, lightweight way of integrating computer applications. REST APIs are a simple and standardized approach to communication, which means you don’t have to worry about how to format your data, it’s all standardized and industry use.

REST APIs are scalable as well, which means as your service scales, you don’t have to worry about the growing complexity. You can easily make modifications to your data and keep track of that across Clients and Servers. They support caching which ensures high performance in large part. This guide will uncover essential knowledge and working principles behind Spring Boot REST APIs in the upcoming sections.

Читайте также:  Php array assigning values

What is JAVA Spring Boot?

As discussed, Spring Boot is a Java-based framework used to create stand-alone, production-grade Spring-based Applications with ease. There are two words here, Spring and Boot. Spring is a huge framework that lets you write enterprise JAVA applications, and Boot is a bootstrap that lets you bootstrap a Spring application from scratch. This is how it gets its name, Spring Boot.

Key Features of Spring Boot

  • Ability to create stand-alone Spring Applications and Microservices with minimal configuration and setup.
  • Can automatically configure Spring Libraries and third-party libraries as well.
  • Access to powerful features such as Key Metrics, Health Checks, and Externalized Configuration.
  • Simplifies your build configuration by providing opinionated ‘starter’ dependencies.
  • Requires no code generation or XML configuration.
  • Build RESTful Web Services for enterprise applications with ease using Spring Boot REST APIs.

Simplify REST API ETL and Data Integration using Hevo’s No-code Data Pipeline

Hevo Data is a No-code Data Pipeline that offers a fully managed solution to set up data integration from 100+ Data Sources (including 30+ Free Data Sources like REST APIs) and will let you directly load data to a Data Warehouse or the destination of your choice.

It will automate your data flow in minutes without writing any line of code. Its fault-tolerant architecture makes sure that your data is secure and consistent. Hevo provides you with a truly efficient and fully automated solution to manage data in real-time and always have analysis-ready data.

Let’s look at some of the salient features of Hevo:

  • Fully Managed: It requires no management and maintenance as Hevo is a fully automated platform.
  • Data Transformation: It provides a simple interface to perfect, modify, and enrich the data you want to transfer.
  • Real-Time: Hevo offers real-time data migration. So, your data is always ready for analysis.
  • Schema Management: Hevo can automatically detect the schema of the incoming data and map it to the destination schema.
  • Scalable Infrastructure: Hevo has in-built integrations for 100’s of sources that can help you scale your data infrastructure as required.
  • Live Monitoring: Advanced monitoring gives you a one-stop view to watch all the activities that occur within Data Pipelines.
  • Live Support: Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.

Prerequisites

To build a Spring Boot REST API with Java, you’re required to have:

Building a Spring Boot REST API in Java

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

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.

Читайте также:  Json encode date php

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

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

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 ListfindAllUsers() < // Implement >@GetMapping("/") public ResponseEntity 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 findAllUsers()

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

@GetMapping("/") public ResponseEntity findUserById(@PathVariable(value = "id") long id) < Optionaluser = 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)

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.

Читайте также:  Запустить cpp файл через командную строку

Step 6: Compile, Build and Run

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

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.

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.

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.

That’s it, you have now successfully tested your Spring Boot REST API.

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 Data offers strong integration with 100+ Sources & BI tools such as SaaS applications, REST APIs, Databases, Files, etc. Hevo’s native REST API connector allows you to not only export data from sources & load data in the destinations, but also transform & enrich your data, & make it analysis-ready so that you can focus only on your key business needs and perform insightful analysis using BI tools.

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.

Источник

Оцените статью