Categories
Java SpringBoot

How to make API call from SpringBoot application?

To make an API call from a Spring Boot application, you can use the RestTemplate or WebClient class provided by Spring. These classes offer methods for making HTTP requests and handling the responses. Here’s how you can make an API call using RestTemplate:

  1. Add the necessary dependency to your pom.xml file if you haven’t already done so. The RestTemplate class is available in the spring-web module, so make sure you have the following dependency:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. In your Spring Boot application, create an instance of RestTemplate and use its methods to make the API call. You can inject it as a dependency in your class or create a new instance.
@RestController
public class MyRestController {

    private final RestTemplate restTemplate;

    public MyRestController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/api/call")
    public String makeAPICall() {
        String apiUrl = "https://api.example.com/endpoint";
        ResponseEntity<String> response = restTemplate.getForEntity(apiUrl, String.class);
        return response.getBody();
    }
}
  1. In the above example, the makeAPICall() method sends a GET request to the specified API endpoint (https://api.example.com/endpoint) and retrieves the response as a ResponseEntity object. You can then extract the response body using response.getBody() and return it from the endpoint.
  2. By default, RestTemplate uses a simple HTTP connection pool and blocking I/O. If you’re using Spring Boot 2.1 or later, it’s recommended to use WebClient instead of RestTemplate. The WebClient class is non-blocking and provides a more flexible and reactive approach to making API calls.
@RestController
public class MyRestController {

    private final WebClient webClient;

    public MyRestController(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.build();
    }

    @GetMapping("/api/call")
    public Mono<String> makeAPICall() {
        String apiUrl = "https://api.example.com/endpoint";
        return webClient.get()
                .uri(apiUrl)
                .retrieve()
                .bodyToMono(String.class);
    }
}
  1. In the WebClient example, the makeAPICall() method returns a Mono<String> instead of a plain String. Mono is a reactive type that represents a potentially asynchronous result. You can handle it asynchronously using reactive programming techniques.

These are the basic steps to make an API call from a Spring Boot application. Depending on your requirements, you can customize the request headers, handle request parameters, handle error responses, and perform other operations using the available methods of RestTemplate or WebClient.

Categories
Java SpringBoot

How to write simple REST API call in SpringBoot

In Spring Boot, you can create RESTful APIs using the Spring Web module, which provides convenient annotations and classes for building RESTful endpoints. Here’s a step-by-step guide to creating a REST API in Spring Boot:

1. Set up a new Spring Boot project or use an existing one. You can use Spring Initializr (https://start.spring.io/) to generate a basic project structure with the required dependencies.

2. Create a new Java class for your REST controller. This class will handle incoming HTTP requests and define the API endpoints. Annotate the class with `@RestController` to indicate that it’s a REST controller.

“`java@RestControllerpublic class MyRestController { // API endpoints will be defined here}“`

3. Define your API endpoints as methods within the controller class. Use appropriate annotations to specify the HTTP method (`@GetMapping`, `@PostMapping`, `@PutMapping`, `@DeleteMapping`, etc.) and the URL path for each endpoint.

“`java@RestControllerpublic class MyRestController { @GetMapping(“/api/greeting”) public String getGreeting() { return “Hello, World!”; } @PostMapping(“/api/user”) public User createUser(@RequestBody User user) { // Process the user object and return a response }}“`

4. In the example above, the `getGreeting()` method handles GET requests to `/api/greeting` and returns a simple greeting string. The `createUser()` method handles POST requests to `/api/user`, expecting a JSON payload in the request body representing a `User` object. You can define your own custom classes like `User` to model the request and response payloads.

5. Within each endpoint method, you can implement the necessary business logic and return the desired response. The response can be a simple string, an object, or a collection of objects. Spring Boot automatically serializes objects to JSON (or XML) based on the request’s `Accept` header.

6. Run your Spring Boot application. By default, Spring Boot will start an embedded Tomcat server that listens for incoming HTTP requests.

7. You can now test your REST API endpoints using a tool like cURL, Postman, or any web browser. For example, to test the `getGreeting()` endpoint, open a browser and navigate to `http://localhost:8080/api/greeting`. You should see the “Hello, World!” message returned.That’s it! You’ve created a basic REST API using Spring Boot. You can add more endpoints, handle request parameters, implement data persistence, and perform other advanced operations as per your application’s requirements.