Java spring boot rest api

Java spring boot rest api DEFAULT

Introduction

REST stands for REpresentational State Transfer, a standardized approach to building web services.

A REST API is an intermediary Application Programming Interface that enables two applications to communicate with each other over HTTP, much like how servers communicate to browsers.

RESTful is the most common approach for building web services because of how easy it is to learn and build.

Let's say you order something from a fast-food restaurant and the cashier requests the information needed from you to process your order. After it's been processed, they hand you the order you requested for. This transaction is a real-life example of how REST API works.

In this tutorial, we'll go over how to build a REST API in Java with Spring Boot. It'll accept and request payloads to view and add entries from an entity - .

Requirements

  • IDE or text editor
  • JDK 1.8+
  • Maven 3+ or Gradle 4+ (We will be relying on Maven for this article)

Initializing a Spring Boot Project

Using Spring Initializr

One easy way you can initialize a new Spring Boot project is by using Spring Initializr, which automatically generates a skeleton Spring Boot project for you:

We'll add a few dependencies here as well, as we'll want to use them in our project:

  • Spring Web - To include Spring MVC and embedded Tomcat into your project
  • Spring Data JPA - Java Persistence API and Hibernate
  • Spring Boot DevTools - Very useful development tools
  • MySQL Driver - JDBC Driver (Can be any DB you'd like to use)

Afterward, press generate. A zip file that contains the generated project will then be downloaded.

Using Spring CLI

If you have Spring CLI installed, then you can opt for using the console to build your base project using this command:

Note: Spring CLI directly calls Spring Initializr to perform this operation. Both options will produce the same project.

After building your base project, download and import it to your IDE or text editor of choice. If you want to build, compile, and run your application through your IDE, make sure you import it as a Maven or Gradle project.

Upon importing, the generated base in your project will look like this:

All the configurations that you did will be reflected in this file. On top of that, default dependencies, your base snapshot , and the Maven build plugin are also automatically configured.

For reference, if you want to build a Gradle Project, your will look like this:

Connecting Spring Boot to the Database

Next, before we start working on the application, we'll want to set up the database. This can easily be done through Spring Data JPA, which allows us to set this connection up with just a couple of parameters.

It abstracts away everything needed to be done by the developer, and allows us to switch underlying databases if we'd like, just by changing a couple of properties.

To tell Spring how to connect to your preferred database, in your file, you'll need to add some rudimentary information:

Here, we've set the to our JDBC connection URL. This depends on your database. We've provided the and required to authenticate into that database, as well as set the property to . The property directly influences the property, and essentially defines how Hibernate should handle schema tool management.

For production applications, this value is typically set to , as dedicated personnel conduct management. In development, it's most common to use , to allow the schema to be updated each time you restart the application, allowing you flexibility while working on development.

Finally, we've set the property. Hibernate has different dialects for different databases. It can automatically set the dialect based on your configuration, though, for additional safety, it's always a good idea to specify it explicitly.

Domain Model - Creating a User Model

Now that the database connection is up and running, we can go ahead and jump into the Domain Model. This is a set of classes, or rather models, we'll use in our application. With Hibernate, they are also called Entities, as well as annotated by the annotation.

Each is picked up by Hibernate, a table is created for it, fields are mapped, and it becomes a managed entity for the database you've set up.

First, let's create a simple entity. We'll annotate the class with and the optional annotation to specify the name for our table.

If not set, it'll just use the same name as the class:

To annotate a field as the of an entity, you use the annotation, and it'll be set as the auto-incrementing, primary key of the table. Additionally, you can additionally set that it's a and set the to .

This is the default setting, if you omit the annotation. Other values you can set are , and . These warrant an article of their own on Hibernate.

Additionally, you can set annotations for each of the fields, providing a name for each of them if you'd like custom names - , would save the field as instead of just .

If you'd like to automate the generation of constructors, getters and setters and just avoid the boilerplate code in total, you can use nifty tools like Lombok.

This class (entity) is now registered with Hibernate. If we run the application, considering our setting, the table will show up in your respective database, with the correct table and mappings for the data types.

Persistence Layer - Creating Repository Classes

Next, let's work on the Persistence Layer. We'll want to have a to perform CRUD operations on our entities. To do this, we'll specify an interface that extends , and annotate it with .

is a variant of the annotation, which lets Spring know that it's a component that should be managed by the IoC container. Specifically, repositories are meant to define logic for the persistence layer.

The extenssion accepts the entity class, as well as the data type it should use to query:

declares methods like , , and which constitute the basic CRUD functionality of a repository. You can use this as-is, to perform CRUD operations on entities now, with no further setup required.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

You can override some of this behavior, if you'd like, though, it's set up automatically to help you bootstrap some basic functionality.

Business Layer - Creating a Controller

Finally, we've gotten to the Business Layer, where we implement the actual business logic of processing information, and use the components from the Persistence Layer, alongside the Domain Model to store data.

Let's create a controller, mark it as a , as we're creating a REST API, and add a to it. is just a combination of and , which means that instead of rendering pages, it'll just respond with the data we've given it. This is natural for REST APIs - returning information once an API endpoint has been hit.

If you'd like to read more about and its Derived Variants, we've got a great article dedicated just to that topic!

Let's go ahead and make a :

We've our . It's used for dependency injection, as the repository class is a dependency here.

If you'd like to read more about Core Spring Framework Annotations, check out our guide!

We've also used the and annotations to specify which types of HTTP requests our methods are accepting and handling. These are derived variants of the annotation, with a set for the respective types.

Let's start off with the implementation for the endpoint:

This method just calls the to users, and returns the list as the response.

Next, let's implement the endpoint to get each user by their :

A with the given might not be present in the database, so we wrap the returned in an .

If you'd like to read more about Optional in Java 8, we've got an in-depth guide!

Then, if the , we return a HTTP response and set the instance as the body of the response. Else, we return a .

Finally, let's make an endpoint to save users:

The method from the user repository saves a new user if it doesn't already exist. If the user with the given already exists, it throws an exception. If successful, it returns the persisted user.

The annotation is a validator for the data we provide about the user, and enforces basic validity. If the user info is not valid, the data isn't saved. Also, the annotation maps the body of the request sent to the endpoint to the instance we'd like to save.

If you'd like to read more about Getting the HTTP Body in Spring Boot, we've got you covered!

Now, it's time to run the app and test if it works.

Compile, Build, and Run

The default port that Spring Boot runs in is . If you want to change the port for whatever reason, you can set it up in your file:

If you have an IDE like IntelliJ that has extensive support for running Spring Boot projects, then you may go ahead and run it that way.

If not, we'll be using the command line to run our project. We can run the application directly by executing (or if you're using Gradle) on the command line from your base project folder where is located.

Another option is to package your application into a file and running it that way.

To do this, we just have to execute ( in Gradle) and run the jar file by executing this command:

If you're using Gradle, the path to the jar file will be different:

You will know when your application has successfully run if you see these audit logs at the end of your command line:

Testing the APIs

Now that your application is up and running on , we can now test the endpoints to see if they work.

For the requests, we can use browsers, or Postman - whatever's most convenient for you.

Let's hit the endpoint with a request:

Or, in your browser address bar, visit , and your browser will display a JSON response:

We can modify this URL to include a path parameter, the to get a specific user. Let's send an HTTP GET request to :

Finally, let's send a HTTP POST request and add a user to our database, by providing the data required in our model. The fields in the JSON payload have to match the field names in our DB/model:

The API will return 200 as a response with this as the response body of the persisted user:

Conclusion

There you have it. You've successfully built your very own Spring Boot REST API!

In this tutorial, we've built a fully functioning Spring Boot project that exposes an API to the end user. Using this API, a user can perform CRUD operations on a entity.

We've covered the Domain Model, Persistence Layer, as well as the Business Layer, after setting up the connection to the database and configuring the project.

Sours: https://stackabuse.com/build-a-spring-boot-rest-api-with-java-full-guide/

In this spring rest tutorial, learn to create REST APIs using Spring boot 2 framework which return JSON responses to client. In this Spring Boot 2 REST API tutorial, we will create two simple GET and POST APIs step by step and test them.

1. Maven dependencies

At first, create a simple maven web project and update following spring boot dependencies in file.

The important dependencies are (read more) and (read more). Starter web dependency transitively includes more dependencies to build a web application such as spring-webmvc, spring-web, hibernate-validator, tomcat-embed-core, tomcat-embed-el, tomcat-embed-websocket, jackson-databind, jackson-datatype-jdk8, jackson-datatype-jsr310 and jackson-module-parameter-names.

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.howtodoinjava.demo</groupId> <artifactId>springbootdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringBootDemo</name> <description>Spring Boot2 REST API Demo for http://howtodoinjava.com</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

2. Spring Boot 2 REST API Controller

  • In Spring, a controller class, which is capable of serving REST API requests, is called rest controller. It should be annotated with @RestController annotation.
  • The resource uris are specified in @RequestMapping annotations. It can be applied at class level and method level both. Complete URI for an API is resolved after adding class level path and method level path.
  • We should always write produces and consumes attributes to specify the mediatype attributes for the API. Never reply on assumptions.

In given controller, we have two API methods. Feel free to add more methods as needed.

  1. HTTP GET /employees – Returns list of the employees.
  2. HTTP POST /employees – Add an employee in the employees collection.
package com.howtodoinjava.rest.controller; 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 com.howtodoinjava.rest.dao.EmployeeDAO; import com.howtodoinjava.rest.model.Employee; import com.howtodoinjava.rest.model.Employees; @RestController @RequestMapping(path = "/employees") public class EmployeeController { @Autowired private EmployeeDAO employeeDao; @GetMapping(path="/", produces = "application/json") public Employees getEmployees() { return employeeDao.getAllEmployees(); } @PostMapping(path= "/", consumes = "application/json", produces = "application/json") public ResponseEntity<Object> addEmployee(@RequestBody Employee employee) { 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(); } }

We can control and customize a lots of implementation details using file. But to keep this demo simple, I am leaving it blank.

3. @SpringBootApplication

Our REST APIs skeleton is ready. Now we need to configure Spring to detect our rest controller (using auto scanning) and deploy apis in embedded tomcat server. Thankfully, Spring boot makes all these things very easy by using the concept of auto configuration.

Auto-configuration attempts to guess and configure beans we you are likely to need. Auto-configuration classes are usually applied based on the jars in application classpath and the beans we have defined additionally in @Configuration classes.

In this case, it does following things.

  1. It detects spring-webmvc so configure default spring mvc application beans. It help in scan and configure and similar annotations.
  2. It detects embed tomcat jars so configure embedded tomcat for us.
  3. It detects JSON jars so configure JSON support to APIs.
package com.howtodoinjava.rest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringBootDemoApplication.class, args); } }

4. Model classes and DAO

These classes are not directly related to REST. Still lets take a look how they have been written.

package com.howtodoinjava.rest.model; public class Employee { public Employee() { } 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; //Getters and setters @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; } } package com.howtodoinjava.rest.model; import java.util.ArrayList; import java.util.List; public class Employees { private List<Employee> employeeList; public List<Employee> getEmployeeList() { if(employeeList == null) { employeeList = new ArrayList<>(); } return employeeList; } public void setEmployeeList(List<Employee> employeeList) { this.employeeList = employeeList; } }

DAO class uses a static list to store data. Here we need to implement actual database interaction.

package com.howtodoinjava.rest.dao; import org.springframework.stereotype.Repository; import com.howtodoinjava.rest.model.Employee; import com.howtodoinjava.rest.model.Employees; @Repository public class EmployeeDAO { private static Employees list = new Employees(); static { list.getEmployeeList().add(new Employee(1, "Lokesh", "Gupta", "[email protected]")); list.getEmployeeList().add(new Employee(2, "Alex", "Kolenchiskey", "[email protected]")); list.getEmployeeList().add(new Employee(3, "David", "Kameron", "[email protected]")); } public Employees getAllEmployees() { return list; } public void addEmployee(Employee employee) { list.getEmployeeList().add(employee); } }

5. Spring Boot REST Demo

To start the application, run the method in class. It will start the embedded tomcat server. In server logs, you will see that API have been registered in spring context.

s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/employees/],methods=[GET],produces=[application/json]}" onto public com.howtodoinjava.rest.model.Employees com.howtodoinjava.rest.controller. EmployeeController.getEmployees() s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/employees/],methods=[POST], consumes=[application/json], produces=[application/json]}" onto public org.springframework.http.ResponseEntity <java.lang.Object> com.howtodoinjava.rest.controller. EmployeeController.addEmployee( com.howtodoinjava.rest.model.Employee )

5.1. HTTP GET /employees

Once server is UP, access the API using some rest client.

Spring Boot REST HTTP GET
{ "employeeList": [ { "id": 1, "firstName": "Lokesh", "lastName": "Gupta", "email": "[email protected]" }, { "id": 2, "firstName": "Alex", "lastName": "Kolenchiskey", "email": "[email protected]" }, { "id": 3, "firstName": "David", "lastName": "Kameron", "email": "[email protected]" } ], }

5.2. HTTP POST /employees

Spring Boot REST HTTP POST

Hit the GET request again and this time we will get the added employee as well.

Spring Boot REST HTTP GET - Updated

6. More examples

  1. Spring @Controller and @RestController Annotations

Let me know if you have query in this spring boot restful web services json example.

Happy Learning !!

Download Sourcecode

References:

Spring boot starters

Let us know if you liked the post. That’s the only way we can improve.

Sours: https://howtodoinjava.com/spring-boot2/rest/rest-api-example/
  1. Fallen order sith
  2. Clean tan reviews
  3. Popping out blackheads
  4. Panini gay

How to create a REST API using Spring Boot, Maven, and MySQL

One benefit of REST APIs is the flexibility and scalability it gives to our application. Since the client and server are independent, the REST protocol separates the data storage from the User Interface in the server.

With this, our application can be scaled quickly, primarily due to the separation of concerns (the separation of the frontend from the server), which helps our application be loosely coupled. This also offers flexibility in modifying our code in the future, as developers can easily integrate RESTful API without much-added work.

Goal

This article teaches how to create a Spring Boot RESTful API that performs CRUD operations by making a database call to a MySQL database using Hibernate - an implementation of JPA (Java Persistence API).

In this tutorial, we will be building an employee management system that registers employees, read, update and deletes employee’s information.

You will also learn how to document your APIs using Swagger UI.

Key takeaways

  • How to create and set up a Spring Boot application with a tomcat server.
  • MySQL database Configuration in a Spring Boot project.
  • You will learn how to implement Object Relational Mapping using Hibernate.
  • Maven for dependency management.
  • Exception handling in Java.
  • How to consume a REST API using postman.
  • How to document API using Swagger.

Prerequisites

To fully understand this tutorial, you are required to have the following in place:

  • A good understanding of Java.
  • A little understanding of the Spring framework and Spring Boot.
  • Java Development Kit (JDK) installed or click on this link to install.
  • Postman API testing tool installed or click on this link to download and install.
  • Maven dependency manager installed or click on this link to download and install.
  • IntelliJ code editor installed or click on this link to install.

Project initialization and setup

There are different ways to set up a new Spring Boot application. We will be using Spring Initializer.

Method 1: Setup using IntelliJ

In this tutorial, we are going to learn how to initialize a Spring Boot project using IntelliJ.

Intellij has inbuilt extensions to create a Spring Boot project using Spring initializer, which makes it easier to set up a project in no time at all.

To get started Run and click to create a new project from .

The next step is to select (highlighted with green).

IntelliJ-Spring-initializer

NOTE: If you look at the highlighted in Red, you will realize that we are connecting to the Spring initializer on the web.

Follow the below steps to set it up:

  • Enter the Maven project properties and click
  • Give the project a name. Let’s call it .
  • Choose the location where you want your project to reside.
  • For the of project, choose .
  • The for this project will be .
  • Let’s name the as .
  • Let’s call the as .
  • Select the Java using the dropdown list.
  • Select your too.
  • We are going to package our project as a file.

JAR is an acronym for Java ARchive. It comes in a ZIP file format and is used for aggregating many files into one. 

Select the Spring Boot version (I’ve selected 2.5.2) and other required dependencies for your project. The correct Spring Boot starters will be added based on the selected dependencies added in the file.

After selecting these dependencies click the button as shown:

select-dependencies-image

This project will have three dependencies namely:

  • : Makes your project a web application. The dependency transitively pulls in all dependencies related to web development. It uses Spring MVC, REST, and Tomcat as a default embedded server.
  • : Allow us to persist data in SQL databases using Spring Data and Hibernate, which is an implementation of the JPA.

JPA is a specification that is part of Java EE (Enterprise Edition) and defines an API for Object-Relational Mappings (ORM) and for managing persistent objects and relational databases. It is considered a standard approach for Object Relational Mapping.

Being that JPA is a specification, it does not perform any operation by itself. Hibernate is one of those ORM (Object Relational Mapping) tools that implements JPA. Others include TopLink, MyBatis.

  • : It is a dependency that connects the MySQL database to a spring boot application.

Method 2: Setup using Spring Initializer

Alternatively, if you are not using IntelliJ you can use the Spring Initializer to set up your project.

Enter the properties including the dependencies as we did above and click on the button. This will generate a file and download it for you. Unzip it and open in your favorite code editor and sync the dependencies with Maven.

spring-initializer-image

Maven dependency management

The file houses the dependencies, and Maven plugins in our project.

The dependency section simply contains the dependencies we added to the project namely MySQL Driver, Spring Data JPA, and SpringWeb.

Here is a sample of file:

Configuring MySQL, JPA, and Hibernate

In the resources folder within the folder, open the file and write the properties below.

  • : Springboot uses the URL along with the credentials (Here, the MySQL is configured with port 3306, and the database name as ) to establish a database connection to our MySQL database.
  • & properties are the MySQL database username and password. (Please use the correct username and password of the MySQL server installed on your computer).
  • The default Spring boot port is . I’ve configured the port of our Spring Boot application to run on .
  • : The SQL dialect makes Hibernate generate better SQL for the chosen database.
  • We have set out DDL (Data definition language) to .

For example, the operation will attempt to add new columns, constraints, etc., but will never remove a column or constraint that may have existed previously, but no longer is as part of the object model.

  • Other values include drops objects on the schema leaving an empty database anytime you rerun your application. It is suitable when you are running a test.

Entry point of the application

By simply initializing your project, your application is ready to be run.

That’s the beauty of Spring Boot, it makes it easier to create stand-alone, production-grade Spring based Applications that you can “just run”.

Locate the file in the folder.

Spring Boot applications should have an entry point class with the method, which is annotated with the annotation and will be used to bootstrap the application.

When launched, the annotation informs the Spring framework to scan for Spring components inside this package and register them.

It also tells Spring Boot to enable , a process where beans are automatically created based on classpath settings, property settings, and other factors.

The annotation is composed of three other annotations namely , , and that helps in automatic configuration. So, we can call it a shortcut for the three annotations.

Now, run the application. You can do this by either clicking on the play button on your IDEA or running this command: on your command line.

Navigate to the root of the project via the command line and execute the command.

Boom! Tomcat started on port .

run-app-image

Project structure

We are going to structure our code into four packages as follows:

  1. Data: This subpackage will house our Data access layer, that will include our Domain and repository.
  2. Service: This is where our business logic will be.
  3. Web: This package will house our controllers.
  4. Exceptions: The is where all our custom exceptions will be.

Throwing exceptions is very important in building a resilient system.

This structure will ensure that the client does not have direct access to our database, rather the request is redirected via controllers.

Controller calls the right service (the business logic) using repository, which in turn makes a call to our database. This architecture also ensures the separation of concerns.

Below is the project structure:

project-structure-image

Creating the domain class

In the data , create another package called .

Inside the package, create an called .

is used as a constant in Java. The properties are implicitly and . Enums are primarily used to specify all the constants that are not going to be mutated. For example, the days of the week.

The department enum class should contain the following code:

Create another class called with the following code:

  • annotation tells Spring that the class which is simply a POJO (Plain Old Java Object) which should be persisted on the database.
  • annotation makes the field the primary key of the employee table when it is persisted on the database.
  • We have used the annotation to specify the primary key generation strategy. The value instructs the database to automatically generate a value for the field. Therefore, the will be generated automatically.
  • annotation converts the enum into a String.
  • Next, we created a no-argument constructor, setters and getters for our field, and override the , , and methods.

Adding additional Maven dependencies

In this section, we are going to add additional dependencies to the project.

Go to Maven Repository and search for the following dependencies and add them to the dependencies section of the file:

  • Javax validation: It is used to validate the fields of an object before persisting to the database.
  • Io springfox: A dependency that will allow us to document our APIs.
  • Add the two dependencies below into the dependencies tag of the .
  • Sync the newly added dependencies to the application.

Payloads

Inside the data package, create a package with the name .

This package will have two sub-packages and to handle our request payloads and response payloads respectively.

Request payload

Inside the request package create an class with the following code:

  • and : These two annotation checks and validate the fields where they are mapped to ensure the values are not blank and null.
  • : It validates that the annotated field is a valid email address.
  • Next, we created setters and getters for the class’s instance variables.

Response payload

Inside the response package create an class with the following code:

  • The code above is a simple POJO with one instance variable, a constructor, a mutator (setters), and an accessor (getters).

Repository

Inside the data package, create a sub-package called . Then, create an interface called that extends .

The is generic, so it takes a model class (Type) and the data type of the primary key.

Write the following code in the interface:

  • makes the interface a bean. It is treated identically to the annotation, therefore it is a specialization of the annotation. Beans are simply Java classes that spring knows.
  • By extending the interface we inherit the , , methods.

Employee service

Create a package under the package.

This package is going to house our business logic. To ensure more separation of concerns, we are going to divide our service into two parts - an interface where the methods of our business logic will be declared and a concrete class that implements the interface.

Create an interface with the name with the following code:

  • annotation is a shorthand for the annotation. It registers the EmployeeService interface as a bean in the application context and makes it accessible during classpath scanning.
  • We created five methods that allow us to create, update, get, and delete employees.

Next, create an class that implements the interface as shown:

  • @Service is specifically a collection of library methods that manage one aspect of an application business logic. It is a specialized form of . With the annotation, the class is registered in the application context and accessible during classpath scanning.
  • The annotation is used to perform field dependency injection. It automatically injects the which is the dependent bean into the class so we can use it. This is possible because is annotated with the annotation making it a bean.
  • The class implemented the EmployeeService interface by overriding the method and implementing them.
  • The class throws an exception (- This is the custom exception class we created that extends ) where the Id supplied to get a single employee does not exist on the database.

Controller

Create a package called under the employee_app package. This package is going to house the APIs controller.

Create an EmployeeController class with the following code:

  • : This annotation marks the EmployeeController as an HTTP request handler and allows Spring to recognize it as a RESTful service.
  • annotation sets the base path to the resource endpoints in the controller as /employee.
  • Next, we autowired the EmployeeService into our controller to use the methods declared implemented in it. This is dependency injection.
  • is a shortcut for , and is used to map HTTP GET requests to the mapped controller methods. We used it to return all the employees and a single employee.
  • annotation shows that a method parameter should be bound to a URI template variable.
  • is a shorthand for @RequestMapping where the method is equal to POST. It is used to map HTTP POST request to the mapped controller methods.
  • : This annotation takes care of binding the web request body to the method parameter with the help of the registered HttpMessageConverters. So when you make a POST request to the “/employee/add” URL with a Post JSON body, the HttpMessageConverters converts the JSON request body into a Post object and passes it to the addEmployee method.
  • is a shorthand for @RequestMapping where the method is equal to PUT. It is used to map HTTP PUT request to the mapped controller methods.
  • : Using this annotation makes the Mapped controller method be ready for a delete operation. It is a shortcut for .

Testing with Postman

Now, let’s test our APIs with Postman.

Adding an employee record

Let’s re-run the application and then add an employee by making a request to .

addemployee-image

Let’s check our MySQL database to confirm again. Boom! There we go.

check-MySQL-image

Get all employee records

Make a request to to get all the employees. I have added two employees already.

getEmployee-image

Boom! It has returned a list of all the employees. We can check MySQL Workbench again.

check-MySQL-again-image

Get a single employee record

Make a request to , specifying the ID of the employee at the end of the URL. In our case, is .

getSingeEmployee-image

Update an employee record

Make a request to specifying the ID of the employee at the end of the URL. In our case, is 3. Add the fields to update as a requestBody.

updateEmployee-image

Deleting an employee record

Make a request to adding to the end of the URL the ID of the todo to delete. In our case, the is 3. We got a showing a successful delete operation.

deleteEmployee-image

We got a showing a successful delete operation. If we check the MySQL database we should have only two employees left having deleted one employee. We deleted the employee with ID as 3.

Documenting the API with Swagger UI

We already added the dependency to the .

With this dependency, we will document the APIs so that they will be easy for other developers to use. Add the below at the class level of your .

  • We added the annotation from swagger at the class level.
  • Go to to access the documentation and test that our APIs are still working properly.
  • Use the Swagger API documentation at to add an employee, get, update, and delete an employee.

Swagger-ui-image

Conclusion

We have successfully built APIs using Spring Boot, Maven as the dependency management tool, and MySQL to store data.

You’ve learned how to throw exceptions in your application in other to build a resilient system. You have also learned how to document your API using Swagger.

You can clone the project on this Git Repository.

Happy coding!


Peer Review Contributions by: Srishilesh P S


About the author

Eme Anya Lekwa

Eme is a Sofware Engineer. He is passionate about how technology can be employed to ensure good governance and citizen political engagement. He is a mobile, web developer and a technical writer.

Sours: https://www.section.io/engineering-education/how-to-create-a-rest-api-using-spring-boot-maven-and-mysql/
Spring Boot Java Tutorial - REST API using PostgreSQL and JWT

How to create a REST API using Java Spring Boot

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:
  2. Now, we need to create a storage class which stores the list of all the employees:
  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:
  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:
  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:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notesarrow_drop_up
Sours: https://www.geeksforgeeks.org/how-to-create-a-rest-api-using-java-spring-boot/

Boot rest api java spring

In this post, we will learn how to create REST API with Spring Boot, JPA, Hibernate, and MySQL.

  1. Create the Spring Boot Project.
  2. Define Database configurations.
  3. Create an Entity Class.
  4. Create JPA Data Repository layer.
  5. Create Rest Controllers and map API requests.
  6. Create Unit Testing for API requests and run the unit testing.
  7. Build and run the Project.

Requirement

We need to create a simple REST API to store user data to MySQL database with that API so we can create, update, delete, and get users information.

Create the Spring Boot Project

First, go to Spring Initializr and create a project with below settings

createproject.png

Web — Full-stack web development with Tomcat and Spring MVC

DevTools — Spring Boot Development Tools

JPA — Java Persistence API including spring-data-JPA, spring-orm, and Hibernate

MySQL — MySQL JDBC driver

Actuator — Production-ready features to help you monitor and manage your application

Generate, download, and import to development IDE.

Define Database Configurations

Next Create the database name called user_database in MySQL database server and define connection properties in spring-boot-rest-api-tutorial/src/main/resources/application.properties

Create Entity Class

Create JPA Data Repository Layer

Create Rest Controllers and Map API Requests

Create Unit Testing for API Requests and Run the Unit Testing

Build and Run the Project

Alternatively, you can run the app without packaging it using:

The app will start running at http://localhost:8080.

The complete source code is here.

Sours: https://dzone.com/articles/how-to-create-rest-api-with-spring-boot
Spring Boot Restful Web Services Tutorial - Full Course ✅ - REST API - Spring Boot for Beginners

Spring Boot - Building RESTful Web Services



Spring Boot provides a very good support to building RESTful Web Services for enterprise applications. This chapter will explain in detail about building RESTful web services using Spring Boot.

Note − For building a RESTful Web Services, we need to add the Spring Boot Starter Web dependency into the build configuration file.

If you are a Maven user, use the following code to add the below dependency in your pom.xml file −

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

If you are a Gradle user, use the following code to add the below dependency in your build.gradle file.

compile('org.springframework.boot:spring-boot-starter-web')

The code for complete build configuration file Maven build – pom.xml is given below −

<?xml version = "1.0" encoding = "UTF-8"?> <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

The code for complete build configuration file Gradle Build – build.gradle is given below −

buildscript { ext { springBootVersion = '1.5.8.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.tutorialspoint' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') }

Before you proceed to build a RESTful web service, it is suggested that you have knowledge of the following annotations −

Rest Controller

The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and custom response. Its syntax is shown below −

@RestController public class ProductServiceController { }

Request Mapping

The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce object. The default request method is GET.

@RequestMapping(value = "/products") public ResponseEntity<Object> getProducts() { }

Request Body

The @RequestBody annotation is used to define the request body content type.

public ResponseEntity<Object> createProduct(@RequestBody Product product) { }

Path Variable

The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {} as shown below −

public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) { }

Request Parameter

The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it is a required parameter. We can also set default value for request parameters as shown here −

public ResponseEntity<Object> getProduct( @RequestParam(value = "name", required = false, defaultValue = "honey") String name) { }

GET API

The default HTTP request method is GET. This method does not require any Request Body. You can send request parameters and path variables to define the custom or dynamic URL.

The sample code to define the HTTP GET request method is shown below. In this example, we used HashMap to store the Product. Note that we used a POJO class as the product to be stored.

Here, the request URI is /products and it will return the list of products from HashMap repository. The controller class file is given below that contains GET method REST Endpoint.

package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId("1"); honey.setName("Honey"); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId("2"); almond.setName("Almond"); productRepo.put(almond.getId(), almond); } @RequestMapping(value = "/products") public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } }

POST API

The HTTP POST request is used to create a resource. This method contains the Request Body. We can send request parameters and path variables to define the custom or dynamic URL.

The following example shows the sample code to define the HTTP POST request method. In this example, we used HashMap to store the Product, where the product is a POJO class.

Here, the request URI is /products, and it will return the String after storing the product into HashMap repository.

package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; 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.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = "/products", method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productRepo.put(product.getId(), product); return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED); } }

PUT API

The HTTP PUT request is used to update the existing resource. This method contains a Request Body. We can send request parameters and path variables to define the custom or dynamic URL.

The example given below shows how to define the HTTP PUT request method. In this example, we used HashMap to update the existing Product, where the product is a POJO class.

Here the request URI is /products/{id} which will return the String after a the product into a HashMap repository. Note that we used the Path variable {id} which defines the products ID that needs to be updated.

package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; 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.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK); } }

DELETE API

The HTTP Delete request is used to delete the existing resource. This method does not contain any Request Body. We can send request parameters and path variables to define the custom or dynamic URL.

The example given below shows how to define the HTTP DELETE request method. In this example, we used HashMap to remove the existing product, which is a POJO class.

The request URI is /products/{id} and it will return the String after deleting the product from HashMap repository. We used the Path variable {id} which defines the products ID that needs to be deleted.

package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; 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.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE) public ResponseEntity<Object> delete(@PathVariable("id") String id) { productRepo.remove(id); return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK); } }

This section gives you the complete set of source code. Observe the following codes for their respective functionalities −

The Spring Boot main application class – DemoApplication.java

package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

The POJO class – Product.java

package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

The Rest Controller class – ProductServiceController.java

package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; 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.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId("1"); honey.setName("Honey"); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId("2"); almond.setName("Almond"); productRepo.put(almond.getId(), almond); } @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE) public ResponseEntity<Object> delete(@PathVariable("id") String id) { productRepo.remove(id); return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK); } @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK); } @RequestMapping(value = "/products", method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productRepo.put(product.getId(), product); return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED); } @RequestMapping(value = "/products") public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } }

You can create an executable JAR file, and run the spring boot application by using the below Maven or Gradle commands as shown −

For Maven, use the command shown below −

mvn clean install

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

For Gradle, use the command shown below −

gradle clean build

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

You can run the JAR file by using the command shown below −

java –jar <JARFILE>

This will start the application on the Tomcat port 8080 as shown below −

Started Application on Tomcat Port8080

Now hit the URL shown below in POSTMAN application and see the output.

GET API URL is: http://localhost:8080/products

POSTMAN Application Get API URL

POST API URL is: http://localhost:8080/products

POSTMAN Application Post API URL

PUT API URL is: http://localhost:8080/products/3

POSTMAN Application Put API URL

DELETE API URL is: http://localhost:8080/products/3

POSTMAN Application Delete API URL
Sours: https://www.tutorialspoint.com/spring_boot/spring_boot_building_restful_web_services.htm

You will also like:

.



955 956 957 958 959