Consultar una API REST pública

A continuación, explicaré cómo consultar una API REST pública, ya sea desde el navegador como desde un programita en java.

La API que voy a utilizar es: https://jsonplaceholder.typicode.com, en concreto users.

Consultar desde el navegador

Para obtener la información que devuelve el servicio users, introduciremos en la barra de direcciones de un navegador: https://jsonplaceholder.typicode.com/users

El resultado es la salida de una lista de usuarios en formato json. Si quieres saber más de json, consulta su web oficial: https://www.json.org/json-es.html.

Salida de la consulta:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  },
…
…
…
]

Observa en la web principal de esta API https://jsonplaceholder.typicode.com/ los métodos disponibles (para nuestro caso sustituimos posts por users):

Routes

All HTTP methods are supported.

GET /posts
GET /posts/1
GET /posts/1/comments
GET /comments?postId=1
GET /posts?userId=1
POST/posts
PUT/posts/1
PATCH/posts/1
DELETE/posts/1

Ejemplo:

Mostrar el usuario cuyo nombre sea Patricia Lebsack.

https://jsonplaceholder.typicode.com/users?name=Patricia Lebsack

Consultar desde programa java

Para obtener información más precisa y si los métodos disponibles no nos resultan útiles, crearemos un pequeño programita en java, donde accederos por código al servicio y parsearemos el resultado.

En este caso queremos obtener el usuario cuya ciudad sea: Aliyaview. Ten en cuenta que el resultado que devuelve está en formato json y no tiene un elemento root o padre y la complejidad a la hora de poder rescatar y tratar la información será algo mayor.

Pasos a realizar:

  • Crea un proyecto web dinámico en eclipse y configúralo con Maven.
  • A continuación incluyo las clases para la resolución:

PeticionRest.java

Clase java principal desde la que iniciaremos el programa.

package es.rosamarfil.cliente;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;

import org.json.JSONArray;
import org.json.JSONObject;

import es.rosamarfil.modelo.User;
import es.rosamarfil.modelo.User.Address_;
import es.rosamarfil.modelo.User.Company;
import es.rosamarfil.modelo.User.Geo;

public class PeticionREST {

	public static void main(String[] args) {

		String URL_API = "https://jsonplaceholder.typicode.com/users";

		// Cliente para la conexión
		Client client = ClientBuilder.newClient();
		// Definición de URL
		WebTarget target = client.target(URL_API);
		// Recogemos el resultado en una variable String
		String response = target.request(MediaType.APPLICATION_JSON).get(String.class);
		// Escribimos por consola el resultado de json
//		System.out.println(response);

		//Almacenamos la información del json en una lista java
		ArrayList<User> listUser = saveJsonToList(response);
		
		//Llamada a procedimiento que imprime el registro buscado
		showUserByCity("Aliyaview", listUser);
		
	}

	private static void showUserByCity(String string, ArrayList<User> listUser) {
		for (int i = 0; i < listUser.size(); i++) {
			if (listUser.get(i).getAddress().city.equalsIgnoreCase(string)){
				System.out.println("El usuario con ciudad " + string + " es: \n" + listUser.get(i));
			}
		}
		
	}

	private static ArrayList<User> saveJsonToList(String response) {

		ArrayList<User> listUser = new ArrayList<User>();
		
		User user;
		Address_ address = null;
		Geo geo = null;
		Company company = null;
		
		JSONObject jsonUser;

		JSONArray jsonarray = new JSONArray(response);

		for (int i = 0; i < jsonarray.length(); i++) {

			jsonUser = jsonarray.getJSONObject(i);

			user = new User();
			user.setId(jsonUser.getInt(User.ID));
			user.setName(jsonUser.getString(User.NAME));
			user.setUsername(jsonUser.getString(User.USERNAME));
			user.setEmail(jsonUser.getString(User.EMAIL));
			user.setPhone(jsonUser.getString(User.PHONE));
			user.setWebsite(jsonUser.getString(User.WEBSITE));

			if (jsonUser.get(User.ADDRESS) != null) {
				JSONObject jsonAddress = jsonUser.getJSONObject(User.ADDRESS);
				address = new User().new Address_();
				address.setStreet(jsonAddress.getString(User.STREET));
				address.setSuite(jsonAddress.getString(User.SUITE));
				address.setCity(jsonAddress.getString(User.CITY));
				address.setZipcode(jsonAddress.getString(User.ZIPCODE));

				if (jsonAddress.get(User.GEO) != null) {
					JSONObject jsonGeo = jsonAddress.getJSONObject(User.GEO);

					geo = new User().new Geo();
					geo.setLat(jsonGeo.getString(User.LAT));
					geo.setLng(jsonGeo.getString(User.LNG));
					address.setGeo(geo);
				}
			}

			if (jsonUser.get(User.COMPANY) != null) {
				JSONObject jsonCompany = jsonUser.getJSONObject(User.COMPANY);
				company = new User().new Company();
				company.setName(jsonCompany.getString(User.C_NAME));
				company.setCatchPhrase(jsonCompany.getString(User.CATCHPHRASE));
				company.setBs(jsonCompany.getString(User.BS));

			}

			user.setAddress(address);
			user.setCompany(company);

			listUser.add(user);
		}

//		imprimirLista(listUser);
		return listUser;
	}

	private static void imprimirLista(List<User> listUser) {
		for (int i = 0; i < listUser.size(); i++) {
			System.out.println(listUser.get(i));
		}

	}
}


User.java

Clase que representa a cada usuario. Este tipo de clases suelen llamarse Bean.

package es.rosamarfil.modelo;

import java.io.Serializable;

public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	// User
	public static String ID = "id";
	public static String NAME = "name";
	public static String USERNAME = "username";
	public static String EMAIL = "email";
	public static String ADDRESS = "address";
	public static String PHONE = "phone";
	public static String WEBSITE = "website";
	public static String COMPANY = "company";

	// Address
	public static String STREET = "street";
	public static String SUITE = "suite";
	public static String CITY = "city";
	public static String ZIPCODE = "zipcode";
	public static String GEO = "geo";

	// Geo
	public static String LAT = "lat";
	public static String LNG = "lng";

	// Company
	public static String C_NAME = "name";
	public static String CATCHPHRASE = "catchPhrase";
	public static String BS = "bs";

	public int id;

	public String name;

	public String username;

	// @JsonProperty(value = "email")
	public String email;

	public Address_ address;

	public String phone;

	public String website;

	public Company company;

	public User(Address_ address, Company company) {
		super();
		this.address = address;
		this.company = company;
	}

	public User() {
	}

	public void setId(int i) {
		this.id = i;
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Address_ getAddress() {
		return address;
	}

	public void setAddress(Address_ address) {
		this.address = address;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getWebsite() {
		return website;
	}

	public void setWebsite(String website) {
		this.website = website;
	}

	public Company getCompany() {
		return company;
	}

	public void setCompany(Company company) {
		this.company = company;
	}


	public class Address_ {

		public String street;

		public String suite;

		public String city;

		public String zipcode;

		public Geo geo;

		public String getStreet() {
			return street;
		}

		public void setStreet(String street) {
			this.street = street;
		}

		public String getSuite() {
			return suite;
		}

		public void setSuite(String suite) {
			this.suite = suite;
		}

		public String getCity() {
			return city;
		}

		public void setCity(String city) {
			this.city = city;
		}

		public String getZipcode() {
			return zipcode;
		}

		public void setZipcode(String zipcode) {
			this.zipcode = zipcode;
		}

		public Geo getGeo() {
			return geo;
		}

		public void setGeo(Geo geo) {
			this.geo = geo;
		}

		@Override
		public String toString() {
			return "Address_ [getStreet()=" + getStreet() + ", getSuite()=" + getSuite() + ", getCity()=" + getCity()
					+ ", getZipcode()=" + getZipcode() + ", getGeo()=" + getGeo() + "]";
		}

	}
	
	public class Company {

		public String name;
		public String catchPhrase;

		public String bs;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getCatchPhrase() {
			return catchPhrase;
		}

		public void setCatchPhrase(String catchPhrase) {
			this.catchPhrase = catchPhrase;
		}

		public String getBs() {
			return bs;
		}

		public void setBs(String bs) {
			this.bs = bs;
		}

		@Override
		public String toString() {
			return "Company [getName()=" + getName() + ", getCatchPhrase()=" + getCatchPhrase() + ", getBs()=" + getBs()
					+ "]";
		}
	}

	public class Geo {

		public String lat;

		public String lng;

		public String getLat() {
			return lat;
		}

		public void setLat(String string) {
			this.lat = string;
		}

		public String getLng() {
			return lng;
		}

		public void setLng(String lng) {
			this.lng = lng;
		}

	}

	@Override
	public String toString() {
		return "User [id=" + getId() + ", name=" + getName()
				+ ", username=" + getUsername() + ", email=" + getEmail() + ", \naddress=" + getAddress()
				+ ", phone=" + getPhone() + ", website=" + getWebsite() + ", \ncompany=" + getCompany()
				+ "]";
	}

}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>ClienteRest</groupId>
	<artifactId>ClienteRest</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.1</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>

		<!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>javax.ws.rs-api</artifactId>
			<version>2.1.1</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-client -->
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-client</artifactId>
			<version>2.12</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.json/json -->
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20180813</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.scalastuff/json-parser -->
		<dependency>
			<groupId>org.scalastuff</groupId>
			<artifactId>json-parser_2.11</artifactId>
			<version>2.0.2</version>
		</dependency>


        </dependencies>
</project>

Resultado:

El usuario con ciudad Aliyaview es: 
User [id=8, name=Nicholas Runolfsdottir V, username=Maxime_Nienow, email=Sherwood@rosamond.me, 
address=Address_ [getStreet()=Ellsworth Summit, getSuite()=Suite 729, getCity()=Aliyaview, getZipcode()=45169, getGeo()=es.rosamarfil.modelo.User$Geo@671a5887], phone=586.493.6943 x140, website=jacynthe.com, 
company=Company [getName()=Abernathy Group, getCatchPhrase()=Implemented secondary concept, getBs()=e-enable extensible e-tailers]]
Consultar una API pública

Evidentemente se puede formatear la salida para que quede más ordenado, se puede dividir la clase User.java en varias clases, etc. ya al gusto de cada uno. Pero a groso modo, ya has aprendido a recoger la respuesta de un WebService Rest y almacenarla en una lista Java.

También te podría gustar...

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *