you can do using webClint to do this
Define a WebClient bean in a @Configuration class so that it can be injected anywhere.
@Configuration
public class WebClientConfig {
@Value("${api.football.token}") // Load token from properties
private String apiToken;
@Bean
public WebClient webClient(WebClient.Builder builder) {
return builder
.baseUrl("https://api.football-data.org/v4")
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiToken) // Set default headers
.build();
}}
Modify DataLoader to use the WebClient bean:
@Component public class DataLoader implements CommandLineRunner { private final ObjectMapper mapper; private final CountryRepository repository; private final WebClient webClient;
public DataLoader(ObjectMapper mapper, CountryRepository repository, WebClient webClient) {
this.mapper = mapper;
this.repository = repository;
this.webClient = webClient;
}
@Override
public void run(String... args) throws Exception {
String response = webClient.get()
.uri("/competitions/PL")
.retrieve()
.bodyToMono(String.class)
.block(); // Blocking (not recommended for web apps, but okay for CommandLineRunner)
JsonNode json = mapper.readTree(response);
JsonNode areas = getAreas(json);
List<Country> countries = new ArrayList<>();
for (JsonNode area : areas) {
countries.add(createCountryFromNode(area));
}
repository.saveAll(countries);
}
private Country createCountryFromNode(JsonNode area) {
String code = area.get("countryCode").asText();
String name = area.get("name").asText();
return new Country(code, name);
}
private JsonNode getAreas(JsonNode json) {
return Optional.ofNullable(json)
.map(j -> j.get("areas"))
.orElseThrow(() -> new IllegalArgumentException("Invalid JSON Object"));
} }
Store your API token securely in application.properties
Store your API token securely in application.properties
webClint is little batter than resttemplate couse
Future-proof: RestTemplate is deprecated in Spring Boot 3. Better Performance: Handles multiple requests efficiently. Flexibility: Works in both blocking and non-blocking modes. Modern: Officially recommended by Spring.