top of page
Search

How to call an API with Java.

Knowing how to make API requests is a key skill for anyone looking to develop code that can connect with the world. Nowadays, you can find APIs on the market that can do practically everything, and it is through a request that you connect to them. In this post, I will demonstrate how to make a simple GET request to an API using Java and the GSON package to work with the returned JSON.



What is an API?


First of all, if the concept of an API is still not very clear to you, I recommend accessing the last post on this website where the idea of what an API is was better explained. Having this knowledge base will be essential for you to understand some topics in this post.


Some technical details to pay attention to:


For compatibility purposes, I inform you that all the code was developed with Java version 1.8.0 and the GSON package version 2.8.7.


Furthermore, to facilitate your learning, I have provided the code used in the example, as well as the GSON library's .jar file, in a GitHub repository available by clicking here.



About the API we will be querying:

Since the goal here is to perform a simple query, we will use a very basic CRM query API available here as an example. This API expects the attributes of the search for the desired doctor to be sent in the request, and it returns the corresponding doctor's data in JSON format. Please note that to make queries to this API, you need to register on the API's website so that they provide a token to monitor the number of queries being made. In this case, you can make up to 100 queries for free. Additionally, I recommend using this API only for learning purposes. When comparing the returns from this API with the returns from the official API of the Federal Council of Medicine, I noticed some inconsistencies in the information.



Now, let's get started...


After setting up the basic Java project structure, we can start implementing our query:


1 - Import the classes we will use in the process:


import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection;
import java.net.URL; import java.util.List; 
import java.util.Scanner;

import com.google.gson.Gson;


2 - Define the classes that will receive the objects returned by the API:


As mentioned above, the API in question will return the result of our query in JSON format. Therefore, to be able to manipulate the return, we will implement a class that will receive this JSON object returned by the API. Through this instantiation, we can work with this return more easily.


class ReturnData {

    private final String url;
    private final String total;
    private final String status;
    private final String message;
    private final String apiLimit;
    private final String apiQueries;
    private final List<Item> item;

    public ReturnData(String url, String total, String status, String message, String apiLimit, String apiQueries, List<Item> item) {
        this.url = url;
        this.total = total;
        this.status = status;
        this.message = message;
        this.apiLimit = apiLimit;
        this.apiQueries = apiQueries;
        this.item = item;
    }
}

In addition to this ReturnData class we created, notice that one of the attributes of this class is a list, and it is expected that this list will be composed of other JSON objects. Therefore, we also need to define a class that can receive these objects:



class Item {

    private final String tipo;
    private final String nome;
    private final String numero;
    private final String profissao;
    private final String uf;
    private final String situacao;

    public Item(String tipo, String nome, String numero, String profissao, String uf, String situacao) {
        this.tipo = tipo;
        this.nome = nome;
        this.numero = numero;
        this.profissao = profissao;
        this.uf = uf;
        this.situacao = situacao;
    }
        
    @Override
    public String toString() {
    	// Returns only the registration status, which is what we want in this case. However, all attributes of the Item class could be returned if necessary.
        return situacao;
    }
}

In this case, in the highlighted line, we only defined the return of this class as the registration status attribute. However, all attributes of the Item class could be returned if necessary.



3 - Define the method to return the list of Items in the Dados_Retorno class:



  	public String getSituacaoCadastral() {
    	
    	String[] itens = item.stream().map(String::valueOf).toArray(String[]::new);
    	
    	if (itens == null) {
    		return "Médico não encontrado!"; // "Doctor not found!" in English
    	} else {
    		return itens[0];
    	}
}

Here, we transform our list into an array and in the method itself, we check if any records were returned in the query. If the number of records is not zero, the specific record is returned (or rather, only the "situation" attribute, which is what we defined to be returned in the Item class).



4 - Perform the query:


After preparing the ground to receive the result of our query, we can define it in the main method as follows (In this case, to provide the complete code, I have included explanations about each line within the code itself):



public class API_Return_Treatment {

	public static void main(String[] args) {
			
		Gson gson = new Gson(); // Instantiate Gson
			
		Scanner sc = new Scanner(System.in); // Receive query data
			
		System.out.print("TYPE: ");
		String type = sc.next();
			
		System.out.print("STATE: ");
		String state = sc.next();
			
		System.out.print("REGISTRATION: ");
		String name = sc.next();

		try {
			// Below, in addition to inserting the user inputs in the API call URL, we establish the connection;
			URL url = new URL("https://www.consultacrm.com.br/api/index.php?type="+type+"&uf="+state+"&q="+name+"&chave=1185342101&destino=json");
				
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("GET");
				
			if (connection.getResponseCode() != 200) { // Handling a possible connection error;
				System.out.print("ERROR... HTTP error code: " + connection.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));

			String output, result = ""; 
				 
			while ((output = br.readLine()) != null) {
				result += output; // In this while loop, the entire API response is added to the 'result' variable
			}
				
			Dados_Retorno dados_retorno = gson.fromJson(result, Dados_Retorno.class); // Takes the JSON returned by the API and puts it into the class we created at the beginning;
				
			System.out.println(dados_retorno.getSituacaoCadastral());

			connection.disconnect();

		} 
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Note that in the highlighted section where the API registration key is inserted, the registration entered is mine. In your consultation I recommend that you use your own to ensure that you enjoy the 100 monthly accesses available for free.



DONE!!!


After executing the steps above, you can now put your code to run and make your own queries to this API.


If this post helped you in any way, share this content with your friends. If you have any suggestions or comments about the post, please contact me and I will respond as soon as possible! To the next!



Comments


Como está o seu currículo?

Ter um bom currículo é uma fator chave para você ter seu trabalho reconhecido perante o mercado de trabalho.

 

Sabemos que elaborar um bom currículo que descreva bem suas habilidade e suas expectativas pode ser uma tarefa muito complicada.

Clique no botão abaixo para ter todo o suporte necessário na elaboração de um currículo nota 10.

Como está o seu currículo?

Ter um bom currículo é uma fator chave para você ter seu trabalho reconhecido perante o mercado de trabalho.

 

Sabemos que elaborar um bom currículo que descreva bem suas habilidade e suas expectativas pode ser uma tarefa muito complicada.

Clique no botão abaixo para ter todo o suporte necessário na elaboração de um currículo nota 10.

Sobre o Autor

"Olá meu nome é Tiago Stasaitis, sou formado

Técnico em Informática e bacharel em Sistemas de Informação.

   

Fundei o Acadêmico Tech no intuito de compartilhar conteúdo que pode ajudar pessoas a se desenvolverem pessoal e profissionalmente. "

1633903387510.jpg
  • LinkedIn - Black Circle
  • Instagram
bottom of page