Cómo Leer Una API con Spring Framework

Github

En alguna ocasión necesitamos leer los datos de una API con Spring Framework o Spring Boot.

Hacerlo es muy fácil, solo debes seguir ciertos pasos que te compartiré a continuación.

En este tutorial te enseñaré a Cómo Leer Una API con Spring Framework, vamos con ello.

Leyendo una API con Spring Framework

Creación de Nuevo Proyecto

Ejecutamos el siguiente comando para crear un nuevo proyecto, le daré el nombre miapp (tu le puedes colocar el nombre que desees):

spring boot new miapp 

Getting project from https://github.com/rd-1-2022/rest-service
Created project in directory 'miapp'

Luego de ejecutar el comando anterior, Spring Framework me ha creado la siguiente estructura de directorios y archivos para el proyecto:

/miapp
  ├── /.mvn
  ├── /.vscode
  ├── /src
  ├── /target
  ├── .gitignore
  ├── LICENSE
  ├── mvnw
  ├── mvnw.cmd 
  ├── porn.xml
  ├── README.adoc

Abrimos el archivo GreetingController.java que se encuentra en miapp > src > main > java > com > example > restservice > greeting > GreetingController.java:

/miapp 
  ├── /.mvn
  ├── /src
      ├── /main
          ├── /java  
              ├── /com 
                  ├── /example 
                      ├── /greeting 
                          ├── Greeting.java   
                          ├── GreetingController.java // Abre este Archivo  
                      ├── /Application.java 
          ├── /test
  ├── /target
  ├── .gitignore
  ├── HELP.md
  ├── mvnw
  ├── mvnw.cmd 
  ├── porn.xml

Dentro del archivo GreetingController.java creamos sobre el final un nueva ruta llamada /api y nueva función para leer la API.

A mi función le daré el nombre leerAPI(), tu le puedes colocar el nombre que desees (He colocado comentarios para explicar que hace cada línea del código):

package com.example.restservice.greeting;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class GreetingController {

	private static final String template = "Hello, %s!";
	private final AtomicLong counter = new AtomicLong();

	@GetMapping("/greeting")
	public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
		return new Greeting(counter.incrementAndGet(), String.format(template, name));
	}

	// Ruta y función para leer la API
	@GetMapping("/api") // Ruta para la API	
	private String leerAPI() {

		// Colocamos la URL de la API 
		String url = "https://nubecolectiva.com/api/v1/postres";

		// Usamos 'RestTemplate', un cliente síncrono para realizar solicitudes HTTP
		RestTemplate restTemplate = new RestTemplate();

		// Obtenemos la respuesta de la API
		String respuesta = restTemplate.getForObject(url, String.class);

		// Imprimimos los datos de la API en la vista HTML
		return respuesta;

	}

}

Probando la API

Iniciamos el servidor de Spring Framework ejecutando el siguiente comando:

./mvnw spring-boot:run

[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< com.example:miapp >--------------------------
[INFO] Building miapp 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] >>> spring-boot-maven-plugin:3.2.3:run (default-cli) > test-compile @ miapp >>>
[INFO]
[INFO] --- maven-resources-plugin:3.3.1:resources (default-resources) @ miapp ---
[INFO] skip non existing resourceDirectory D:\contenidos\nc\tutoriales\blog\miapp\src\main\resources
[INFO] skip non existing resourceDirectory D:\contenidos\nc\tutoriales\blog\miapp\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.11.0:compile (default-compile) @ miapp ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.3.1:testResources (default-testResources) @ miapp ---
[INFO] skip non existing resourceDirectory D:\contenidos\nc\tutoriales\blog\miapp\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.11.0:testCompile (default-testCompile) @ miapp ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] <<< spring-boot-maven-plugin:3.2.3:run (default-cli) < test-compile @ miapp <<<
[INFO]
[INFO]
[INFO] --- spring-boot-maven-plugin:3.2.3:run (default-cli) @ miapp ---
[INFO] Attaching agents: []

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.2.3)

2024-08-15T20:35:51.294-05:00  INFO 22072 --- [           main] com.example.restservice.Application      : Starting Application using Java 17.0.10 with PID 22072 (D:\contenidos\nc\tutoriales\blog\miapp\target\classes started by jrclu in D:\contenidos\nc\tutoriales\blog\miapp)
2024-08-15T20:35:51.297-05:00  INFO 22072 --- [           main] com.example.restservice.Application      : No active profile set, falling back to 1 default profile: "default"
2024-08-15T20:35:52.015-05:00  INFO 22072 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2024-08-15T20:35:52.023-05:00  INFO 22072 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2024-08-15T20:35:52.024-05:00  INFO 22072 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.19]
2024-08-15T20:35:52.063-05:00  INFO 22072 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2024-08-15T20:35:52.064-05:00  INFO 22072 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 736 ms
2024-08-15T20:35:52.364-05:00  INFO 22072 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
2024-08-15T20:35:52.400-05:00  INFO 22072 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path ''
2024-08-15T20:35:52.411-05:00  INFO 22072 --- [           main] com.example.restservice.Application      : Started Application in 1.351 seconds (process running for 1.567)

Si vamos a la ruta local http://localhost:8080/api, podemos ver que Spring Framework lee la API correctamente:

API leída correctamente con Spring Framework
LA API devuelve los datos en formato JSON, tu los puedes mostrar en una tabla HTML de forma más ordenada

Así de fácil puedes leer o consumir una API con el framework Spring.

Conclusión

En este tutorial has aprendido a Cómo Leer Una API con Spring Framework.

Te servirá para que leas diferentes API con el framework Spring.

Practica y practica mucho para que puedas ser un experto en Spring Framework.

Nota(s)

  • No olvides que debemos usar la Tecnología para hacer cosas Buenas por el Mundo.