Creating a POST and GET request Springboot

Mercy Jemosop
Code Crunch

--

When to use params and request body when creating a request spring-boot

Introduction

Overview of spring boot requests and its common annotations

we map requests to request handlers via the @RequestMapping annotation. Spring Boot derived types of this annotation - @GetMapping, @PostMapping, @DeleteMapping…

@RequestBody annotation allows us to retrieve the request's body. We can then return it as a String or deserialize it into a Plain Old Java Object (POJO).

@RestController is a combination of @ResponseBody and @Controller annotation. This will return a response body instead of a templete as the response body.

source

N.B Before getting started, create a database for the project and add your basic depedencies.

Create and connect to postgress database

To get started update your application.properties file

# specify the port your spring boot application will run on
server.port:8082

# data source is a factory for connecting to any physical data source.
spring.datasource.url=jdbc:postgresql://localhost:5432/tables_management

# postgres configurations
spring.datasource.username=your_username
spring.datasource.password=your_password

#This(create and update) should not be used in production
spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto = create

Update your pom.yaml file, the content of this file may vary with your’s depending on what you are working on. Just add the relevant dependencies.

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tables</groupId>
<artifactId>Tables</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Tables</name>
<description>Managing tables springboot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>

<dependency>
<groupId> org.apache.tomcat.embed </groupId>
<artifactId> tomcat-embed-jasper </artifactId>
<scope> provided </scope>
</dependency>

<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

<!-- It allows us to access and persist data between Java object/ class and relational database.-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</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>

POST Request springboot

To handle a post request , we will use we’ll use the @PostMapping annotation for it:

Old format

@RequestMapping(value = "/registration", method = RequestMethod.POST)

new(simpler , i prefer this annotation than the general one)

@PostMapping("/registration")

Controller class with registration method.

We are using a ResponseEntity which represents the whole HTTP response: status code, headers, and body.To use responseEntity, we have to return it from the endpoint

@RestController
public class TutorialController {

@PostMapping("/registration")
public ResponseEntity<?> registerUser() {

return new ResponseEntity("", HttpStatus.OK);
}
}

Create a Domain/entity/database table class where we will post/save/store our data in the database. The getter and setter annotation represent the getter and setter methods. To use this annotations you need to add lombok dependency to your pom.xml. This makes your code clean and easy to read since you won’t need to create a getter and setter method for all your variables

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

Entity class

@Getter
@Setter
@Entity
@Table(name = "customer")
public class Customer{

@Id
@GeneratedValue(strategy = AUTO)
private Long id;
@Column(name="name")
private String name;
@Column(name="age")
private Integer age;
@Column(name="phone_number")
private String phoneNumber;

public Customer() {
}
public Customer(String name, Integer age, String phoneNumber) {
this.name = name;
this.age = age;
this.phoneNumber = phoneNumber;
}
}

The next part is to create a model which will hold our data(RequestBody). Model works as a container that contains the request data of the application. The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. You can give the model class any relevant name.

@Getter
@Setter
public class UserModel {
@JsonProperty("name")
private String name;
@JsonProperty("age")
private Integer age;
@JsonProperty("phone_number")
private String phoneNumber;

public UserModel() {
}

public UserModel(String name, Integer age, String phoneNumber) {
this.name = name;
this.age = age;
this.phoneNumber = phoneNumber;
}
}

Create a user repository that extends JPArepository, this is important inorder to utilize the already created CRUD methods

@Repository
public interface UserRepository extends JpaRepository<Customer,Long> {
}

Finally we update our controller with a request body(Our model, the data which we will pass to be saved). Then pass the data to repository methods to save it.

@RestController
public class TutorialController {

@Autowired
UserRepository userRepository;

@PostMapping("/registration")
public ResponseEntity<?> registerUser(@RequestBody UserModel userModel) {
// get the data passed by user/passed to postman
Customer user = new Customer(
userModel.getName(),
userModel.getAge(),
userModel.getPhoneNumber()
);
//save data passed by user
Customer userSaved = userRepository.save(user);
// return the saved data and an Okay.
return new ResponseEntity(userSaved, HttpStatus.OK);
}
}

Let’s run our application and test it with postman.N.B the name(key) you pass on postman should be the same as that in JsonProperty in your model. Be keen on data types.

Let’s check the database if the record has been updated

Yeeey.

N.B a good Post request requires a good validation. Validate the data in the model class. e.g

/// add @NotBlank annotation to strings
@NotBlank(message="name Address Required")
@JsonProperty("name")
private String name;
/// add @NotNull annotion to an integer
@JsonProperty("age")
@NotNull(message = "age required")
private Integer age;
/// finally on your controller add @Validate annotation inorder to ///validate the annotation passed in the modelpublic ResponseEntity<?> registerUser(@Valid @RequestBody UserModel userModel) {

Get request

Retrieving data from the database. To create a GET request we use RequestParam. N.B we use request body for making POST request.

RequestParam takes a name,value, required which is boolean(specify if the parameter is required or not),default value.

@RequestParam(value = "name") String name,
@RequestParam(value = "age",required = false) String age
@GetMapping("/getUsers")
public ResponseEntity<?> getUser() {

List<Customer> getUser = userRepository.findAll();

return new ResponseEntity(getUser, HttpStatus.OK);
}

The above method is good when learning java but not preferable in production(Retrieving all items in the database,it is good to retrieve only what is required or retrieve a list per page-predicate allows you to do this). Research on predicate, with predicate you can search a list by params, you can set params to not required when getting all items in the list.

JPA also has so many functions you can take advantage of for CRUD API(Create,Read,Write,Update)

Happy coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!.

--

--

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy