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.
Hevo offers robust REST API integrations, allowing you to seamlessly connect and sync data from various APIs to your data warehouse. With Hevo, you can seamlessly integrate data from multiple sources into any data warehouse, ensuring your organization has a unified view of its data assets.
Why Use Hevo for Data Warehouse Integration?
- Broad Source and Destination Support: Connect to over 150+ sources, including databases, SaaS applications, and more, and load data into your preferred data warehouse.
- Real-Time Data Sync: Keep your data warehouse up-to-date with real-time data flow, ensuring your analytics are always based on the latest information.
- No-Code Platform: With Hevo’s user-friendly interface, you can easily set up and manage your data pipeline without any technical expertise.
Get Started with Hevo for Free
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.
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 SpringBoot 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"
}
Integrate REST API to Snowflake
Integrate REST API to BigQuery
Integrate REST API to Redshift
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.
- 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.
- Click on Create new Collection icon in the left panel to create a collection.
- Select Edit -> Type in your “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.
- Provide a request name “Create Employee”. The following diagram shows that:
- Make the HTTP method as POST.
- Type in “https://localhost:8080/api/employees” under the field 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.
- 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;
- To GET employees, go to Enter Request URL field and type in “http://localhost:8080/api/employees/”. Let the Body be empty -> press 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” }
- 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.
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 Rest API Spring Boot
- 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 (60+ 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.
FAQ on RESTful APIs in Spring Boot
How to write a REST API in Spring Boot?
Creating a REST API with Spring Boot involves several steps. Here’s a detailed guide:
– Set Up a Spring Boot project
– Structure your Spring Boot project
– Define Model Class
– Create a Repository Interface
– Create Controller class
– Configure Database
– Run the Application
– Test the API
Which dependency enables to create REST API in Spring Boot application?
To create a REST API in a Spring Boot application, you need to include the spring-boot-starter-web dependency. This starter dependency includes the necessary libraries for building web applications and RESTful services using Spring MVC.
How REST API works step by step?
– Client sends a request
– The request is mapped to a specific controller
– The controller interacts with the repository
– The repository performs necessary database operations
– Response is given back to the client
Raj, a data analyst with a knack for storytelling, empowers businesses with actionable insights. His experience, from Research Analyst at Hevo to Senior Executive at Disney+ Hotstar, translates complex marketing data into strategies that drive growth. Raj's Master's degree in Design Engineering fuels his problem-solving approach to data analysis.