30 June 2020   |   by Jatin Jeena   |   Spring, Blogs

Make Get & Post Api in Spring

Making Get & Post Api in Spring Boot Framework

In this tutorial we will learn and help you how to implement step by step get and post api easily in java in spring boot framework.

Let's begin:

API is the acronym for Application Programming Interface. APIs let our product or service communicate with other products and services.

To create simple GET and POST API in spring you just need to create two simple functions in your Controller.java file.

Just follow these five simple steps:

1. First of all you need to bind your Controller class by RestController annotation, by writing “@RestController” before the class Controller. Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method.

2. Create two functions for the handling the GET and POST request.

3. Bind both the function with PostMapping and GetMapping annotations. PostMapping and GetMapping annotations are used to handle the POST and GET type of requests respectively. Add “@PostMapping” annotation before the function which handles Post request and “@GetMapping” annotations before the function that handles Get request. These two annotations also set the path or address for request, by which the api will be hit.

4. The data that will be given to the api will be received in the request body. For this purpose we will use the annotation RequestBody. “@RequestBody” will be added in the function parameters before declaring the variable for receiving the data.

5. For simplicity we can just print data received by the request or return a simple string as response. All the annotations used in this process will be imported from the org.springframework.web.bind.annotation package.

The above points are presented in the below code.

For testing these apis in postman, make sure the java application(server) is running. Call the apis by selecting the request type and filling its body.

Output of Get API

Output of Post API

The apis ran successfully as we can see the required string displayed on receiving the data in their body.