Home > Java > javaTutorial > How to call third-party API in Spring Boot

How to call third-party API in Spring Boot

Patricia Arquette
Release: 2025-01-23 22:04:15
Original
936 people have browsed it

This Spring Boot tutorial demonstrates how to consume a third-party API and display the results in a Thymeleaf view. Let's refine the text and code for clarity and accuracy.

Revised Text:

Overview

This tutorial guides you through integrating a third-party API into a Spring Boot application. We'll make a GET request to https://api.sampleapis.com/coffee/hot, then elegantly present the response data within a Thymeleaf template displayed in your browser.

Prerequisites

Basic familiarity with the following is assumed:

  • Java
  • Spring Boot
  • Thymeleaf
  • Maven (or Gradle) for dependency management

Development Process

1. Project Setup

Use Spring Initializr (https://www.php.cn/link/bafd1b75c5f0ceb81050a853c9faa911) to create a new Spring Boot project. Include the following dependencies:

How to call third-party API in Spring Boot

Extract the downloaded archive and import the project into your IDE (e.g., IntelliJ IDEA).

2. Create the Coffee Model

Create a POJO (Plain Old Java Object) to represent the coffee data received from the API. This simplifies data handling.

<code class="language-java">package com.myproject.apidemo;

public class Coffee {
    public String title;
    public String description;

    // Constructors, getters, and setters (omitted for brevity)
    @Override
    public String toString() {
        return "Coffee{" +
                "title='" + title + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}</code>
Copy after login

3. Create the CoffeeController

This controller handles the API call and data processing.

<code class="language-java">package com.myproject.apidemo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.core.ParameterizedTypeReference;
import java.util.List;

@Controller
public class CoffeeController {

    @GetMapping("/coffee")
    public String getCoffee(Model model) {
        String url = "https://api.sampleapis.com/coffee/hot";

        WebClient webClient = WebClient.create();

        List<Coffee> coffeeList = webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference<List<Coffee>>() {})
                .block();


        model.addAttribute("coffeeList", coffeeList);
        return "coffee";
    }
}</code>
Copy after login

Note: Error handling (e.g., using onErrorResume with WebClient) should be added for production-ready code. The block() method is used here for simplicity but should be replaced with reactive programming techniques for better performance in a real-world application.

4. Create the Thymeleaf View (coffee.html)

Create a Thymeleaf template to display the coffee data. Place this file in src/main/resources/templates/coffee.html.

<code class="language-html"><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Coffee List</title>
</head>
<body>
    <h3>Coffee List</h3>
    <table>
        <thead>
            <tr>
                <th>Title</th>
                <th>Description</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="coffee : ${coffeeList}">
                <td th:text="${coffee.title}"></td>
                <td th:text="${coffee.description}"></td>
            </tr>
        </tbody>
    </table>
</body>
</html></code>
Copy after login

5. Run the Application

Start your Spring Boot application. You should now be able to access the coffee list at http://localhost:8080/coffee (or your application's base URL).

This revised version provides a more complete and accurate representation of the process, including crucial details like the Coffee model class and improved code formatting. Remember to handle potential errors in a production environment.

The above is the detailed content of How to call third-party API in Spring Boot. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template