banner image
Sedang Dalam Perbaikan

Create a REST API using Java - Spring Boot



Hello everyone! This is another new article..I think the people who read this, will know what Java is. As you know, it's a programming language. Normally JavaSE is used for developing standalone applications. When it becomes to the web development field, we can still use Java but in a different way. There we come across Spring as a framework that makes the easy development of JavaEE applications(web apps). Spring Boot is an opinionated instance of a Spring application. It is a rapid application development platform. It is very easy to develop Spring Based applications with Spring Boot. It provides an already arranged setup for applications with configurations. Spring Boot reduces lots of development time and increases productivity. Simply Spring Boot reduces our coding effort.

How can we use Spring Boot?
In any web project, we can see a working back-end containing its functionalities. We can create web application back-ends, REST APIs, Micorservices using this amazing framework!
Today I will guide to create a simple REST API to perform CRUD operations. My use case will be based on users. In the REST API I create, you can Create, Retrieve, Update and Delete users.

Step 1 - Create a Spring Boot project

1st method
Go to this site. https://start.spring.io/
You can give any name you want and add the dependencies want. Then click on generate project. It will download a zip file containing your project. extract it and open your favorite IDE for Java like IntelliJ IDEA or Eclipse.
Dependencies should be added : Web, Rest Repositories, MongoDB



2nd method (Recommended)
Here I use IntelliJ IDEA. Go to New > Project and select Spring Initializer from the left sidebar. 
*If you can not see Spring Initializer there, 
Open IDE and install plugin to create Spring Boot project from scratch. Click on File > Settings > Plugins and then search for Spring Assistant. Click on browse  repositories and install it. Then you will be asked to restart the IDE. Do it! Now when you go to create a new project you will have Spring Assistant on left sidebar. Select it.

Now you can follow these steps...Simply click on next button..Finally click on finish button. 
Dependencies should be added : WebRest RepositoriesMongoDB


    Give package names according to you want.


    Select the Dependencies


    Give a project name


Now you have a sample Spring Boot application. This is the basic folder structure for a Spring Boot Project.

When you expand com.rest.api or package with the name you provided, you can see a Java Class created by default. It's the main class for our application. To run the project right click on the project and select Run application option. Then it will start running the application.

By default, Spring applications use the PORT 8080. Application will be up listening to the port 8080. You can change this using some configurations.

Step 2 - Create packages 

Mainly we need 3 packages. They are controller, entity and repository. Create them by right clicking on the main package.
controller - contains REST controller
entity - contains Data class
repository - contains MongoDB Interface

Step 3 - Create Entity Class

This is the class that defines the structure of our MongoDB objects to be stored. We have to define the attributes and arrange Getters and Setters to manage them inside this class. I'm going to handle user objects as I earlier said. So I define a user with a name, age and job. My MongoDB collection name is users. Create a new class in the entity package.

package com.rest.api.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "users")
public class User {

@Id
private String id;
private String name;
private String job;
private int age;

public User(){

}

public User(String name, String job, int age){
this.name = name;
this.age = age;
this.job = job;
}

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;
}

public String getJob() {
return job;
}

public void setJob(String job) {
this.job = job;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

Now our object is ready. We have to get the MongoDB functionalities using an Interface. We'll move on to that step.

Step 4 - Create MongoDB Repository Interface

This is the place where we retrieve the MongoDB functionalities to our application. I create a new repository called UserRepository implementing the MongoRepository interface. Then all the methods defined in the MongoRepository class, can be used via the newly created UserRepository class. Create a new class inside the repository package.

package com.rest.api.repository;

import com.rest.api.entity.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends MongoRepository {

}

As the last step, we have to implement the API functionalities through a controller class. Let's create it.

Step 5 - Create a Controller to implement API functionalities

This is the most important part of our project. All the routes relevant to the API are included in the controller class. So, create a class inside the controller package. In my case I named it as UserController.

package com.rest.api.controller;

import com.rest.api.entity.User;
import com.rest.api.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/users")
@CrossOrigin("*")
public class UserController {

@Autowired
private UserRepository userRepository;

//GET ALL USERS
@RequestMapping(method=RequestMethod.GET, value="/")
public List findAllUsers() {
return userRepository.findAll();
}

//GET SINGLE USER
@RequestMapping(method=RequestMethod.GET, value="/{id}")
public Optional getUser(@PathVariable("id") String id) {
return userRepository.findById(id);
}

//ADD USER
@RequestMapping(method=RequestMethod.POST, value="/add")
public User addUser(@RequestBody User user) {
userRepository.save(user);
return user;
}

//UPDATE USER
@RequestMapping(method=RequestMethod.PUT, value="/update")
public void updateUser(@RequestBody User user) {
userRepository.save(user);
}

//DELETE USER
@DeleteMapping("/delete/{id}")
public void deleteUser(@PathVariable("id") String id) {
userRepository.deleteById(id);
}

}

@RequestMapping is the annotation to match routes. In the very first mapping I have included "/users". Therefore, In my all the API calls there is a URI segment called users. Inside this annotation, we can give the method of our request like GET/ POST. I have included them separately for each route. Now my API routes will be;

http://localhost:8080/users/
http://localhost:8080/users/{id}
http://localhost:8080/users/add
http://localhost:8080/users/update
http://localhost:8080/users/delete/{id}

We wire a instance of UserRepository to the controller. Then we can use MongoDB - Java functionalities directly.

Step 6 - Application Configuration

Now our application is ready to go! But there is another small thing! Usually a Spring Boot application is running on port 8080 as I said. If you want to change this? How to do it? And where to connect MongoDB? You must have these question by now. This is the solution. In our application you can see a folder called resources in the main > java package. Open it and find the configuration file called application.properties. Open it and give these configurations..

server.port=8080
spring.data.mongodb.host=localhost
spring.data.mongodb.database=api
spring.data.mongodb.port=27017

Here, api is my MongoDB database running on localhost. Now we have connected our application to the MongoDB. I think our work is over now!

For a further step, this REST API can be tested using a software like Postman or a browser extension like Rest Client. Then we can verify the API is working or not.

Now store some users in the database - api.
When you give an API call to , http://localhost:8080/users/ it will fetch all users stored in the database.


Ok guys! Now you have the REST API built using Spring Boot framework.. You can test this and verify the functionalities. And you can connect this API to and front-end and manage data using UI. Try to create a UI and give API calls to these URLs and get results. I will try to use this REST API with a front-end implemented using React JS, in future. Till then,

Good Bye Guys!



Create a REST API using Java - Spring Boot Create a REST API using Java - Spring Boot Reviewed by DAL on November 09, 2018 Rating: 5

No comments:

Powered by Blogger.