Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring batch item writer rest API

Is it possible to read data from DB, process it and in ItemWriter send to another system using RestAPI (REST TEMPLATE) in Spring batch project? All I can see is fetch data and write it in a csv file.

like image 678
shubham sharma Avatar asked Aug 12 '26 11:08

shubham sharma


1 Answers

It is possible to create your own custom ItemWriter.

In your case, please add the spring-boot-starter-web dependency to either your pom.xml or build.gradle

Example:

package com.example.batch;

import lombok.extern.log4j.Log4j2;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Log4j2
public class RestItemWriter implements ItemWriter<String> {
    @Autowired
    RestTemplate restTemplate;

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

    @Override
    public void write(List<? extends String> items) throws Exception {
        ResponseEntity<Users> users = restTemplate.getForEntity("https://jsonplaceholder.typicode.com/users/1", Users.class);

        log.info("Status code is: " + users.getStatusCode());
    }
}


package com.example.batch;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Users {

    public String id;
    public String name;
    public String username;
    public String email;
    public String phone;
}

More information about custom item writers here

like image 71
Asif A Fasih Avatar answered Aug 14 '26 10:08

Asif A Fasih



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!