How to Create RESTful API service with Spring Boot

How to Create RESTful API service with Spring Boot

This post we'll Building a RESTful service with Spring Boot. You will use those values throughout the rest of this sample.

This is a getting started guide for people interested In spring.

Why Spring Boot for Your Microservices

Spring Boot enables building production-ready applications quickly and provides non-functional features: Embedded servers which are easy to deploy with the containers. It helps in monitoring the multiples components. It helps in configuring the components externally.

Getting Started

Create a new package called clients in the root of your project src as shown below

This is image title

inside this package we will have 4 classes ;

Client.java
ClientController.java
ClientRepository.java
ClientService.java

the client class defines the object class and will aslo be our Entity class that will define the clients table in the database. To handle database transactions we will use the spring data jpa package, this is installed via the pom.xml

 <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-jpa</artifactId>
 </dependency>

we will also need the spring web package that carries functions necessary for handling HTTP requests

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

finally installing the mysql DB drivers

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

after adding the lines above to your dependencies section in the pom.xml run mvn clean install

package com.example.sample.demo.clients;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
**
@Entity
public class Client {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long  id;
    private String name;
    private String email;

    public Client(){

    }


    public Client(Long id, String name, String email){
        super();
        this.id = id;
        this.name = name;
        this.email = email;

    }


    /**
     _ @return Long return the id
     _/
    public Long getId() {
        return id;
    }

    /**
     **_ @param id the id to set
     _**/
    public void setId(Long id) {
        this.id = id;
    }

    /**
     _ @return String return the name
     _/
    public String getName() {
        return name;
    }

   **
    public void setName(String name) {
        this.name = name;
    }

  **
   _
  _
    public String getEmail() {
        return email;
    }

    /_*
     _ @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

}

The code above decribes the Client.java class not moost of the annotations describing the db datatypes have been extended from the java persistence api (jpa) next we will define our ClientRepository.java

ClientRepository

package com.example.sample.demo.clients;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface ClientRepository extends CrudRepository<Client, Long> {

    List<Client> findByName(String name);
}

ClientRepository extends the CrudRepository interface. The type of entity and ID that it works with,Client and Long, are specified in the generic parameters on CrudRepository. By extending CrudRepository, ClientRepositoryinherits several methods for working with Client persistence, including methods for saving, deleting, and finding Client entities.

Spring Data JPA also allows you to define other query methods by simply declaring their method signature. In the case of ClientRepository, this is shown with a findByName() method.

In a typical Java application, you’d expect to write a class that implements ClientRepository. But that’s what makes Spring Data JPA so powerful: You don’t have to write an implementation of the repository interface. Spring Data JPA creates an implementation on the fly when you run the application.

ClientService

The service hadles most of the logic and responses are directly called in the Controller class. The logic below could have well been handled directly in the controller class.

package com.example.sample.demo.clients;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ClientService {

    @Autowired
    private ClientRepository clientRepository;



    public List<Client> getAllClients() {

        List<Client> Clients = new ArrayList<>();
        clientRepository.findAll().forEach(Clients::add);
        return Clients;

    }

    public Optional<Client> findParticularClient(Long id) {

        return clientRepository.findById(id);

    }

    public Boolean createClient(Client client){
        try{
            clientRepository.save(client);
            return true;
        }
        catch(Exception e){
            return false;
        }
    }


    public boolean deleteClientRecord(Long id){
        try{
            clientRepository.deleteById(id);
            return true;
        }
        catch(Exception e){
            return false;
        }
    }


    public boolean updateClientRecord(Client client, Long clientId){
        try{
            clientRepository.save(client);
            return true;
        }
        catch(Exception e){
            return false;
        }
    }




}

ClientController

In Spring’s approach to building web sites, HTTP requests are handled by a controller. You can easily identify these requests by the @Controller

@ResponseBody Binds the http paramenters to variables @Request Method dictates the method handled by the particular route A thing to note is that all responses in the @Controller class are Json Encoded by default this is one of the many adavantages of the spring framework.

package com.example.sample.demo.clients;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/_*
 _ ClientController
 */

@RestController
public class ClientController {

    @Autowired
    private ClientService clientService;

    @RequestMapping(value="/clientDetails", method = RequestMethod.GET)
    public Optional getClient(@RequestParam("id") Long id) {
        return clientService.findParticularClient(id);

    }

    @RequestMapping(value="/clients", method= RequestMethod.GET)
    public List getAllClients() {
        return clientService.getAllClients();
    }

    @RequestMapping(value="/clientCreate", method = RequestMethod.POST)
    public void createClient(@RequestBody Client client) {
        clientService.createClient(client);
    }

    @RequestMapping(value="/clientDelete", method = RequestMethod.DELETE)
    public void deleteClient(@RequestParam("id") Long id) {
        clientService.deleteClientRecord(id);
    }

    @RequestMapping(value="/clientUpdate", method = RequestMethod.PUT)
    public void updateClient(@RequestBody Client client, @RequestParam("id") Long clientId) {
        clientService.updateClientRecord(client, clientId);
    }

}

Database Connection

We are now done with our Rest application we would now like to test it but first we need to connect to the database. find the application.properties file in your main/resources folder

server.port=8090
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/{your-database-name}?useSSL=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

in the same folder create a schema.sql file and add the following

CREATE TABLE client (
    id int AUTO_INCREMENT NOT NULL,
    name VARCHAR (200) NULL,
    email VARCHAR (100) NULL,
    PRIMARY KEY (id)
)

when running the application it is supposed to migrate and map the schema onto your database. or you could just create it the old fashioned way its upto you.

once everything is set up run the application

mvn spring-boot:run

Testing

Using Postman

This is image title

Thank you for reading!

spring-boot microservices java database restful-api

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Securing RESTful API with Spring Boot, Security, and Data MongoDB

A comprehensive step by step tutorial on securing or authentication RESTful API with Spring Boot, Security, and Data MongoDB

Spring Data REST Tutorial: Developing RESTful APIs with Ease

In this article, you will learn how to develop REST APIs with ease by using Spring Data REST and Spring Boot together. Throughout the article, you will scaffold a new Spring Boot application, create a JPA entity, and use Spring Data REST to provide some basic operations over it. Besides that, you will also learn how to validate the data your API is dealing with and how to secure the application.

Spring Boot REST Service: How to build a REST API in Java

In this tutorial, you will learn how to build a basic REST API in Java using Spring Boot.

Spring Boot REST Service: How to build a REST API in Java

You will learn how to build a basic REST API in Java using Spring Boot.

How to Build a CRUD API with Java, MongoDB, and Spring Boot

This tutorial shows how to build a CRUD API with Java, MongoDB, and Spring Boot. How to build a CRUD API with Java and MongoDB. In this tutorial, you create a Java data model class and mapped it to a MongoDB domain document using Spring Data annotations. You use a simple embedded MongoDB database as the datastore. You use Spring Boot to quickly and easily expose your data model via a REST API. Finally, you secured the REST API using Okta and Okta’s Spring Boot Starter.