Open In App

How to create a REST API using Java Spring Boot

Last Updated : 01 Jun, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet. RESTful Web services allow the requesting systems to access and manipulate textual representations of Web resources by using a uniform and predefined set of stateless operations. Other kinds of Web services, such as SOAP Web services, expose their own arbitrary sets of operations.

In this article, we will understand how to create a rest API using spring boot.

Spring is widely used for creating scalable applications. For web applications, Spring provides Spring MVC which is a widely used module of spring which is used to create scalable web applications. But the main disadvantage of spring projects is that configuration is really time-consuming and can be a bit overwhelming for the new developers. The solution to this is Spring Boot. Spring Boot is built on the top of the spring and contains all the features of spring. In this article, we will create a REST API to add employees to the employee list and get the list of employees. In order to do this, we first have to create a simple Spring Boot project in any of the IDE’s and follow the steps:

  1. Initially, we need to define the employee entity. Therefore, the following employee class is defined:




    package com.example.demo;
      
    // Creating an entity Employee
    public class Employee {
      
        public Employee() {}
      
        // Parameterized Constructor
        // to assign the values
        // to the properties of
        // the entity
         public Employee(
            Integer id, String firstName,
            String lastName, String email)
        {
      
            super();
      
            this.id = id;
      
            this.firstName = firstName;
      
            this.lastName = lastName;
      
            this.email = email;
      
               
        }
      
           private Integer id;
      
           private String firstName;
      
           private String lastName;
      
           private String email;
      
        // Overriding the toString method
        // to find all the values
        @Override
       public String toString()
        {
      
            return "Employee [id="
                + id + ", firstName="
                + firstName + ", lastName="
                + lastName + ", email="
                + email + "]";
      
               
        }
      
        // Getters and setters of
        // the properties
        public Integer getId()
        {
      
             return id;
        }
      
        public void setId(Integer id)
        {
      
             this.id = id;
        }
      
        public String getFirstName()
        {
      
             return firstName;
        }
      
        public void setFirstName(
            String firstName)
        {
      
             this.firstName = firstName;
        }
      
        public String getLastName()
        {
      
             return lastName;
        }
      
        public void setLastName(
            String lastName)
        {
      
             this.lastName = lastName;
        }
      
        public String getEmail()
        {
      
             return email;
        }
      
        public void setEmail(String email)
        {
      
             this.email = email;
        }
    }

    
    

  2. Now, we need to create a storage class which stores the list of all the employees:




    package com.example.demo;
      
    import java.util.ArrayList;
    import java.util.List;
      
    // Class to store the list of
    // all the employees in an
    // Array List
    public class Employees {
      
        private List<Employee> employeeList;
      
        // Method to return the list
        // of employees
        public List<Employee> getEmployeeList()
        {
      
            if (employeeList == null) {
      
                employeeList
                    = new ArrayList<>();
      
                       
            }
      
            return employeeList;
      
               
        }
      
        public void
        setEmployeeList(
            List<Employee> employeeList)
        {
            this.employeeList
                = employeeList;
        }
    }

    
    

  3. Till now, we have defined the entity employee and created a storage class. Now, we need to access the employees. So, we create a class from where we will create an object of the storage class to store the employees:




    package com.example.demo;
      
    import org.springframework
        .stereotype
        .Repository;
      
    // Importing the employees class to
    // use the defined properties
    // in this class
    import com.example.demo.Employees;
      
    @Repository
      
    // Class to create a list
    // of employees
    public class EmployeeDAO {
      
        private static Employees list
            = new Employees();
      
        // This static block is executed
        // before executing the main
        // block
        static
        {
      
            // Creating a few employees
            // and adding them to the list
            list.getEmployeeList().add(
                new Employee(
                    1,
                    "Prem",
                    "Tiwari",
                    "chapradreams@gmail.com"));
      
            list.getEmployeeList().add(
                new Employee(
                    2, "Vikash",
                    "Kumar",
                    "abc@gmail.com"));
      
            list.getEmployeeList().add(
                new Employee(
                    3, "Ritesh",
                    "Ojha",
                    "asdjf@gmail.com"));
      
               
        }
      
        // Method to return the list
        public Employees getAllEmployees()
        {
      
            return list;
        }
      
           
            // Method to add an employee
            // to the employees list
            public void
            addEmployee(Employee employee)
        {
            list.getEmployeeList()
                .add(employee);
               
        }
    }

    
    

  4. Finally, we need to create a controller class which is the actual implementation of the REST API. According to the REST rules, every new entry in the database has to be called by the POST method and all the requests from the database must be called using the GET method. The same methods are implemented in the following code:




    package com.example.demo;
      
    import java.net.URI;
    import org.springframework.beans
        .factory.annotation.Autowired;
    import org.springframework.http
        .ResponseEntity;
    import org.springframework.web.bind
        .annotation.GetMapping;
    import org.springframework.web.bind
        .annotation.PostMapping;
    import org.springframework.web.bind
        .annotation.RequestBody;
    import org.springframework.web.bind
        .annotation.RequestMapping;
    import org.springframework.web.bind
        .annotation.RestController;
    import org.springframework.web.servlet
        .support.ServletUriComponentsBuilder;
      
    // Import the above-defined classes
    // to use the properties of those
    // classes
    import com.example.demo.Employees;
    import com.example.demo.EmployeeDAO;
    import com.example.demo.Employee;
      
    // Creating the REST controller
    @RestController
    @RequestMapping(path = "/employees")
    public class EmployeeController {
      
        @Autowired
       private EmployeeDAO employeeDao;
           
            // Implementing a GET method
            // to get the list of all
            // the employees
       @GetMapping(
            path = "/",
            produces = "application/json")
      
        public Employees getEmployees()
        {
      
            return employeeDao
                .getAllEmployees();
        }
      
           
            // Create a POST method
            // to add an employee
            // to the list
       @PostMapping(
            path = "/",
            consumes = "application/json",
            produces = "application/json")
      
        public ResponseEntity<Object> addEmployee(
            @RequestBody Employee employee)
        {
      
            // Creating an ID of an employee
            // from the number of employees
            Integer id
                = employeeDao
                      .getAllEmployees()
                      .getEmployeeList()
                      .size()
                  + 1;
      
            employee.setId(id);
      
            employeeDao
                .addEmployee(employee);
      
            URI location
                = ServletUriComponentsBuilder
                      .fromCurrentRequest()
                      .path("/{id}")
                      .buildAndExpand(
                          employee.getId())
                      .toUri();
      
                   return ResponseEntity
                .created(location)
                .build();
        }
    }

    
    

  5. After implementing all the classes in the project, run the project as Spring Boot App. Once the server starts running, we can send the requests through the browser or postman. We can access the running app by going into the following URL:
    http://localhost:8080/employees/
    

Output: The following is the output generated on running the above project:

  1. When a GET request is performed:
  2. When a POST request is performed:
  3. Again hitting the GET request after performing the POST request:


Previous Article
Next Article

Similar Reads

Easiest Way to Create REST API using Spring Boot
Spring Boot is a powerful framework that makes it easy to create RESTful APIs. In this article, we will go through a step-by-step guide on how to create a RESTful API in Spring Boot with MySQL and JPA. We will start by creating a new Spring Boot project and configuring it for our needs. For developers eager to deepen their knowledge and expertise i
11 min read
JSON using Jackson in REST API Implementation with Spring Boot
Whenever we are implementing a REST API with Spring (Spring Boot), we would have come across the requirement to exclude NULLs in the JSON Response of the API. Also, there might be a requirement to externalize turning ON/OFF this feature: Exclude NULLS in the JSON Response, thereby allowing the consumer of the API to customize as per the need. In th
3 min read
Spring Boot - REST API Documentation using OpenAPI
For any application, API documentation is essential for both users and developers. How to use an API, what will be the request body, and what will the API's response be? API documentation is the answer to all of these questions, springdoc-openapi is a Java library that automates the generation of the API documentation in both JSON/YAML and HTML for
4 min read
Spring Boot – REST API Documentation using Swagger
REST stands for Representational State Transfer. REST is an architectural design pattern that defines constraints that are used in web service development. Swagger is a framework in which we can test our REST APIs for different HTTP requests i.e. : GETPOSTPUTDELETEIn this article, we will be discussing using Swagger for documenting APIs in Spring B
5 min read
Spring Boot - How to set a Request Timeout for a REST API
In Microservice architecture, there are multiple microservices available for an application. For the application to work properly necessary services need to communicate with each other. There can be communication of messaging type or REST calls. How does REST API Work?In REST Calls the process is synchronous, which means suppose a service SERV1 is
7 min read
Spring Boot - Versioning a REST API
API Versioning is a defined process of making or managing changes to an API. These changes can be made transparently without interrupting the clients. When users have permission to decide whether they can conveniently upgrade to the latest version of API and clearly state the changes made is known as a Good API Versioning Strategy. When to Version
3 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
How to Make REST Calls using FeignClient in Spring Boot?
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. FeignClient also known as Spring Cloud OpenFeign is a Declarative REST Client in Spring Boot Web Application.
13 min read
Spring Boot - REST Example
We all know in today's world, most web app follows the client-server architecture. The app itself is the client or frontend part under the hood it needs to call the server or the backend to get or save the data this communication happens using HTTP protocol the same protocol is the power of the web. On the server, we expose the bunch of services th
4 min read
How to Call REST Services with WebClient in Spring Boot?
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring WebClient is a non-blocking and reactive web client to perform HTTP requests. It is also the replaceme
11 min read
How to Create Todo List API using Spring Boot and MySQL?
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
6 min read
Spring MVC - Get Probability of a Gender by Providing a Name using REST API
A lot of funful REST API calls are available as open source. Suppose if we like to keep a name to our nears and dears, we can just check that by means of a REST API call and get the gender, what is the probability of being that gender and how many times does it come with it? Relevant REST API call https://api.genderize.io?name=<Provide your desi
7 min read
Spring MVC - Get Exchange Rate Values using REST API
People are doing business, and developing software for geographical locations. That means the calculation of a software price will vary globally. During those scenarios, we need to know about the exchange rates for a given currency. Nowadays many open source REST API calls are available and among that there is a call available to get exchange rates
5 min read
OpenSource REST API URL and Retrieving Data From it By Using Spring MVC
In this internet era, a lot of helper services are available in the form of REST API and mostly REST API provides us the details in the form of JSON/XML. We can use them in our applications and render the data as we like. Here is the list of a few opensource REST API URLs: API NameDescriptionURLCoinGeckoExchange rates https://api.coingecko.com/api/
6 min read
Spring MVC - Getting Cryptocurrency Details using REST API
Cryptocurrencies are a hot topic throughout the world. Trading with cryptocurrency got both pros and cons. Nowadays REST APIs are very useful to get much information including cryptocurrencies. In this article, we are going to see about one such REST API call to get cryptocurrency detail. We are going to retrieve the information by using Spring MVC
5 min read
Get Time Zone by Providing Latitude and Longitude using Spring MVC and REST API
Spring MVC Framework follows the Model-View-Controller design pattern. It is used to develop web applications. It works around DispatcherServlet. DispatcherServlet handles all the HTTP requests and responses. In this article, we are going to see about a REST API call to find the coordinates for the given latitude and longitude. Each and every area
6 min read
Spring MVC - Comparison of Cryptocurrencies using REST API
REST APIS is available in plenty nowadays. As cryptocurrencies are a hot topic nowadays, there is always a need to compare the different cryptocurrencies and get the corresponding value in different currencies. As a sample, let us take a REST API call as https://min-api.cryptocompare.com/data/price?fsym=LTC&tsyms=BTC,USD,EUR,INR Here fym repres
6 min read
Spring MVC - Last 24 Hour Cryptocurrency Data using REST API
Cryptocurrencies are a hot topic now and in the future; they may also be a payment source. Hence a lot of research is getting done. Many REST APIs are available to provide data in JSON format. We are going to see one such REST API as https://api.wazirx.com/sapi/v1/ticker/24hr?symbol=<Need to provide the symbol of cryptocurrency> Example: http
5 min read
Spring MVC Project - Retrieving Population, Area and Region Details using Rest API
REST API is more popular nowadays as we can able to get a variety of information like Population, Area, region, sub-region, etc., One such REST API that we are going to see here is https://restcountries.com/v3.1/capital/<any capital of a country> Example: https://restcountries.com/v3.1/capital/delhi Corresponding JSON Response: As a Maven Spr
4 min read
How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using Java is that it tries to connect every concept in the language to the real world with the help
3 min read
How to Create and Setup Spring Boot Project in Spring Tool Suite?
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Java Spring Boot Microservices - Integration of Eureka, Feign & Spring Cloud Load Balancer
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
13 min read
Java Spring Boot Microservices - Client Side Load Balancing with Spring Cloud LoadBalancer
Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microservices. Basically, there are two ways to load balanc
12 min read
Java Spring Boot Microservices – Integration of Eureka and Spring Cloud Gateway
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
5 min read
How to Extract TV Show Details via REST API and Spring MVC?
REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring MVC is a Web MVC Framework for building web applications. It is a spring module same as spring boot, s
9 min read
Spring MVC - Get University/College Details via REST API
REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring MVC is a Web MVC Framework for building web applications. It is a spring module same as spring boot, s
6 min read
Spring Boot | How to access database using Spring Data JPA
Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot
4 min read
three90RightbarBannerImg