top of page
maratheashwini5

Creating Restful API using Spring Boot framework

Hello everyone, Nowadays the Client-Server Architecture are mostly used over web. The application has two parts front-end and back-end, where front-end make a HTTP request which intern talk to database and provides required data to client. This article walks you through process of creating your own Restful APIs using Spring Boot framework. Spring Boot is an open source java framework to create a web application. You can run spring boot application using embedded Tomcat server.


Restful APIs to define HTTP methods (GET,POST,PUT,DELETE) ,provide authorization for each endpoints. This article covers writing logic to the services for HTTP methods and how to interact to the database layer. So lets get started..


Prerequisites : In order to create the following Project you need

  1. Eclipse IDE

  2. Postgres(pgAdmin)

  3. Postman

 

Step 1:   Set up your project.

Open the url  https://start.spring.io/ .

This screen allows to provide basic project configuration with required spring boot version, and gives easy way to add all required project dependencies.

 

 

 

      You can add spring security dependency to your project for authentication.Once you click on generate, It provide one zip file, extract the zip and import project in eclipse which is a skeleton of your project.

 

Step 2:  The project created has this EmployeeApiApplication.class which contains main method.

 

 

Step 3: For this application we need a database, you can use any database like mySql, Mongo, SQL Server db etc, Here I am using an Postgres as sql database. Where we are storing the employee records.

 

Create a database employee_db then create a table with columns as employee_id, emp_name, emp_address, salary. 

 

 

Here we have to create a JDBC connection to interact with data layer. Create a java class DBConnection.java

 

public class DBConnection { 

public static Connection getConn() throws Exception {

      String jdbcUrl = "jdbc:postgresql://localhost:5432/employee_db";

      String username = "postgres";

      String password = "password";

      //Enter the username and password of your pgAdmin

      Class.forName("org.postgresql.Driver");

      return DriverManager.getConnection(jdbcUrl, username, password);

}

public static void closeConn(Connection conn) {

   try {

         conn.close();

      } catch (SQLException e) {

         e.printStackTrace();

     }

  }

} 

Step 4: Create a java class EmployeeVo.java which holds POJO for the fields employee_id , emp_name, emp_address, salary. For this project I have used basic Employee POJO with three fields.


Create a Controller Class which handles incoming request and return responses. For this use annotations like

@RestController: It handles REST request. There are four HTTP request methods

@PostMapping("/create/employee") Creates new employee.

@PutMapping("/update/employee/{id}") Updates an existing employee with given id.

@GetMapping("/get/employee/{id}") Retrieve employee with given id.

@DeleteMapping("/delete/employee/{id}") Deletes the employee with id.

Tips:

  • Import the necessary packages import org.springframework.web.bind.annotation.*;

  • Same way you can try for get, delete, put and patch HTTP methods.

@RestController
public class Controller {
	@PostMapping(value="/create/employee",produces = "application/json")
	@ResponseStatus(HttpStatus.CREATED)
	ResponseEntity<?> newEmployee(@RequestBody EmployeeVo newEmployee) {
		return DBOperations.insertEmployee(newEmployee);
	}
	@PutMapping(value="/update/employee/{id}",produces = "application/json")
	@ResponseStatus(HttpStatus.OK)
	ResponseEntity<?> updateEmp(@PathVariable int id,@RequestBody EmployeeVo newEmployee) {
		return DBOperations.updateEmployee(id,newEmployee);
	}
	@GetMapping(value="/get/employee/{id}",produces = "application/json")
	@ResponseStatus(HttpStatus.OK)
	ResponseEntity<?> one(@PathVariable int id) {

		return DBOperations.getEmployee(id);
	}
	@DeleteMapping(value="/delete/employee/{id}",produces="text/plain;charset=UTF-8")
	@ResponseStatus(HttpStatus.OK)
	ResponseEntity<?> delete(@PathVariable int id) {
		return DBOperations.deleteByID(id);
	}
}

Step 4: Create a DBOperations.java class which handles the logic for post, put, get, delete.  Here, I implemented logic for post method which inserts new employee record in database.Given below is the sample code for post method.

Before inserting new employee record, first I am checking if input request is having valid data and if employee with given data already present user will get error with message 'Employee with given data already present'.

Note:Import necessary packages for this class.

public static ResponseEntity<?> insertEmployee(EmployeeVo emp)
	{
		if(!isDataValid(emp))
		{
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid input..");
		}
		Connection conn=null;
		try {

			conn= DBConnection.getConn();

		if(isEmployeePresent(conn,emp.getEmp_name(),emp.getEmp_address(),null))
			{
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Employee with given data already present");
			}
			else
			{
				PreparedStatement ps=conn.prepareStatement("insert into employee (emp_name,emp_address,salary) values (?,?,?)");

				ps.setString(1, emp.getEmp_name());
				ps.setString(2, emp.getEmp_address());
				ps.setFloat(3, emp.getSalary());

				ps.execute();

				ResultSet rs = conn.createStatement().executeQuery("select employee_id from employee"
						+ " where emp_name='"+emp.getEmp_name()+"' and emp_address='"+emp.getEmp_address()+"'");

				int newIDcreated=-1;
				while(rs.next())
				{
					newIDcreated=rs.getInt(1);

				}

				return ResponseEntity.status(HttpStatus.CREATED).body("Inserted new employee record, id : "+newIDcreated);

			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("unable to insert employee record");

		}
		finally
		{
			DBConnection.closeConn(conn);
		}
	}

private static boolean isEmployeePresent(Connection conn, String emp_name, String emp_address, Integer emp_id) throws Exception{

		String query="select employee_id from employee"
				+ " where emp_name='"+emp_name+"' and emp_address='"+emp_address+"'";

		if(emp_id!=null)
			query=query+ " and employee_id != "+emp_id;

		ResultSet rs=conn.createStatement().executeQuery(query);
		while(rs.next())
		{
			return true;
		}

		return false;
	}

	
	public static  boolean isDataValid(EmployeeVo emp){

		if(emp.getEmp_name()==null||emp.getEmp_name().isEmpty()||
				emp.getEmp_address()==null||emp.getEmp_address().isEmpty())	
		{
			return false;
		}
		return true;
	}

Step 5: Now run the EmployeeApiApplication.class which provides the server and the port information. Default port is 8080 but here i changed the port no. This can be done by writing application.properties file


 Here we have application running on http://localhost:9000 is the base url where the end points for the application are for

post operation: /create/employee

put operation: /update/employee/{id}

get operation: /get/employee/{id}

delete operation: /delete/employee/{id}


Step 6: The Employee application is ready to Test. This can done using Postman tool.



 

Step 7: The Employee which is created it reflect in database.

Conclusion : Spring Boot provides convenient way to built RESTful Web Services for enterprise applications.


Reference Links:

  1. Help you create your project structure

2. This will guide you throughout your project


Thank you... For Reading my blog. Learning is fun!


227 views

Recent Posts

See All
bottom of page