Search(Json + Javascript)

Asked

Viewed 307 times

3

I’m a designer and I’m trying to get into this front world...I have some questions.

I’m starting a javascript search that accesses the webservice:https://contas.tcu.gov.br/contrata2RS/api/publico/termos-contratuais

I’ll point out some questions:

1- Is it possible to consume this webservice with javascript only? I’m only using HTML and CSS.

2 - If yes ! Is it possible to treat JSON when the user type in the search field? For example:

It type in the search field the word "School" and the result brings everything that has the word school.

3 - How I can get the result and make it more presentable (using CSS)?

4 - I can choose which fields I want to present? Is it possible to do this filtering?

OBS: I don’t have access to webservice public, so whenever I make the consultation, it will all come.

If anyone has any example or can give me some north, I thank you very much...the examples can be done with just one label very simple research....

2 answers

1

Short answer: it is possible to consume Webservices using only HTML/JS/CSS taking into account some points.

Assuming you only have a few HTML/JS/CSS files, I assume your application is composed of only these static files. When you open your application in the browser probably the first problem you will encounter when consuming this API (address you mentioned) will be with CORS (cross origin Resource sharing). For security reasons the browser blocks requests to this type of API when the API domain is different from its application. To solve this the API should send in the response header some specific keys and values. I suggest to give a read here.

Answers to the other points:

  1. Webservice must be prepared to receive the word that will be used as a filter to return only things related to it. If WS is not prepared for this it is possible to request and process the data using Javascript as long as you have in hand the logic used to filter the information based on the searched word.
  2. Basically formatting the result using Javascript/CSS.
  3. Yes, by using Javascript. There are several functions that help in handling String/Arrays that can collaborate with this task, but it is a very broad theme.

A simple example of how to consume an API and display the result, just to give you a starting point:

https://jsfiddle.net/uLnwp2gc/1/

<button onclick="pesquisar();">Pesquisar</button>
<div id="resultado"></div

Script:

pesquisar = () => {
    fetch('https://www.mocky.io/v2/5185415ba171ea3a00704eed').then(function(response) {
        response.json().then(function(json) {
            console.log('resultado', json);
            document.querySelector('#resultado').innerHTML = JSON.stringify(json);
        });
    });
}|
  • Thank you very much, Marcelo !

  • @Thiagolourenço vlw ;) anything is just talk. abs

1


1- Is it possible to consume this webservice with javascript only? I’m only using HTML and CSS.

1 - No, because this service is blocked for CORS, so you must request this service through the application Backend, otherwise you will receive the following error: Access to XMLHttpRequest at 'https://contas.tcu.gov.br/contrata2RS/api/publico/termos-contratuais' from origin 'https://fiddle.jshell.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource., this happens because you are making a request for another domain that is not released in the Response header.

2 - If yes! Is it possible to treat JSON when the user type in the search field? For example:

2 - Yes, you can make a filter service in javascript after you have taken your data:

3 - How I can get the result and make it more presentable(using CSS)?

3 - It is difficult to answer what is more "presentable", you can create HTML elements and stylize them via class or by inserting individual Tyles and put the data you got in your request.

4 - I can choose which fields I want to present? It is possible to do this filtering?

4 - Yes, after the request, you can manipulate which properties you want to display.

I made an example for you to take a look, there I put examples of how to do what you want for each question

var data = [
    {
        "codigoTipoContratacao": 1,
        "tipoContratacao": "CONTRATO",
        "numero": 2,
        "ano": 2013,
        "unidadeGestora": "ISC",
        "codUnidadeGestora": 160000,
        "nomeFornecedor": "FUNDACAO UNIVERSIDADE DE BRASILIA",
        "cnpjFornecedor": "00038174000143",
        "objeto": "Prestação de serviços educacionais técnico-especializados. Participação de servidores/colaboradores do TCU no curso de Pós-graduação lato sensu em Auditoria Pública, turma 2013.",
        "valorInicial": 326000,
        "dataAssinatura": "2013-08-02T00:00:00-0300",
        "dataInicioVigencia": "2013-08-02T00:00:00-0300",
        "dataTerminoVigencia": "2015-02-28T00:00:00-0300",
        "numeroProcesso": "043.525/2012-1",
        "modalidadeLicitacao": "DISPENSA DE LICITAÇÃO",
        "numeroAditamentos": 0,
        "valorAtualizado": 326000,
        "dataTerminoVigenciaSegundoAditamentos": "2015-02-28T00:00:00-0300",
        "codigo": 2524,
        "codigoModalidadeLicitacao": 48
    },
    {
        "codigoTipoContratacao": 11,
        "tipoContratacao": "REGISTRO DE PREÇOS",
        "numero": 7,
        "ano": 2015,
        "unidadeGestora": "SEGEDAM",
        "codUnidadeGestora": 170000,
        "nomeFornecedor": "DECATRON AUTOMACAO E TECNOLOGIA DE INFORMACAO LTDA",
        "cnpjFornecedor": "00205354000172",
        "objeto": "Fornecimento de solução composta por licenças de uso de produtos VMware, subscrição de suporte telefônico do fabricante e atualização de versão, upgrade de licenças existentes, serviços de suporte on-site e treinamento.",
        "valorInicial": 0,
        "dataAssinatura": "2015-03-13T00:00:00-0300",
        "dataInicioVigencia": "2015-03-19T00:00:00-0300",
        "dataTerminoVigencia": "2016-03-18T00:00:00-0300",
        "dataPublicacao": "2015-03-16T00:00:00-0300",
        "numeroProcesso": "027.454/2014-2",
        "modalidadeLicitacao": "PREGÃO ELETRÔNICO",
        "anoLicitacao": 2015,
        "numeroLicitacao": 3,
        "numeroAditamentos": 0,
        "valorAtualizado": 0,
        "dataTerminoVigenciaSegundoAditamentos": "2016-03-18T00:00:00-0300",
        "codigo": 2779,
        "codigoModalidadeLicitacao": 49
    },
    {
        "codigoTipoContratacao": 1,
        "tipoContratacao": "CONTRATO",
        "numero": 40,
        "ano": 2015,
        "unidadeGestora": "SEGEDAM",
        "codUnidadeGestora": 170000,
        "nomeFornecedor": "RH99 SISTEMAS LTDA",
        "cnpjFornecedor": "08179838000104",
        "objeto": "A aquisição de licenças de uso do sistema de avaliação psicológica Human Guide e a habilitação de servidores do TCU para operá-lo.",
        "valorInicial": 33188,
        "dataAssinatura": "2015-11-03T00:00:00-0200",
        "dataInicioVigencia": "2015-11-03T00:00:00-0200",
        "dataTerminoVigencia": "2017-11-02T00:00:00-0200",
        "dataPublicacao": "2015-11-04T00:00:00-0200",
        "numeroProcesso": "024.177/2015-6",
        "modalidadeLicitacao": "INEXIGIBILIDADE DE LICITAÇÃO",
        "numeroAditamentos": 0,
        "valorAtualizado": 33188,
        "dataTerminoVigenciaSegundoAditamentos": "2017-11-02T00:00:00-0200",
        "codigo": 2864,
        "codigoModalidadeLicitacao": 5
    }
]

function setFilter() {
//Fazendo um serviço de filtro como na dúvida número 2
var result = [];

var filterOnInput = document.getElementById('filter').value;

data.forEach((element) => {
    if(element.numero.toString() == filterOnInput || element.ano.toString() == filterOnInput){
    	result.push(element);
    }
});

document.getElementById('result').innerHTML = JSON.stringify(result);

}

function onload() {

document.getElementById('result').innerHTML = JSON.stringify(data[0]) + JSON.stringify(data[1]) + JSON.stringify(data[2])

var el = document.getElementById('button'); // pega o elemento button


el.addEventListener('click', function() { // no evento click 
  setFilter(); // executa a função filtro
}, false);

var al = document.getElementById('changeDisplay'); // pega o elemento button


al.addEventListener('click', function() { // no evento click 
  displayOnlySomeInfo(); // executa a função filtro
}, false);

}

function displayOnlySomeInfo(){
//dúvida de número 4 mostrar somente algumas infos.
var resultado = "";

data.forEach((element) => {
    resultado = resultado + "<b>Código do tipo contrato: </b>";
		resultado = resultado + element.codigoTipoContratacao.toString() + "\n \n ";
    
});

	document.getElementById('result').innerHTML = resultado;

}

onload()
/* Fazendo estilização do conteúdo como na dúvida número 3*/
.result {
  width: 200px;
  color: blue;
}
<label>Mostrar somente algumas infos</label><br>
<button id="changeDisplay">
Ok!
</button><br><br>

<label>Filtrar por Número ou ano</label><br>
<input id="filter"><br>
<button id="button" onclick="setFilter()">
Ok!
</button><br><br>
<br><label>Resultado</label>
<br>
<p class="result" id="result">

</p>

<p class="result" id="resultado">

</p>

  • Thank you very much for the explanation, Peace. Peace, as I can for example take this field of JSON: "codigoTipoContraction": 1, and leave it so: Contract type code:1. It is possible to place line break so as not to get crowded ?

  • Nothing my good, in case you could change the text that is placed in the foreach function that I did inside the displayOnlySomeInfo(), in the case of line break, you can insert the " n" that makes a line break, or even insert another element of paragraph, I’ll change the answer with what you want

  • Code edited @Thiagolourenço

Browser other questions tagged

You are not signed in. Login or sign up in order to post.