API request and Python

Hello Everyone,

PLease be patient. I’m almost a zero knowledge in coding. But I would like to learn. So please, be patient once the question will be veeeery basic:

I’m learning to use Knack and API with an simple app. The user fill the lawsuit number (processo) in a form and JS should request data from Court. Court provide API access to it (https://datajud-wiki.cnj.jus.br/api-publica/endpoints). I have tested the code using Google Colab and it did work out bringing all results I need.

import requests
import json

url = “https://api-publica.datajud.cnj.jus.br/api_publica_trt2/_search

payload = json.dumps({
“query”: {
“match”: {
“numeroProcesso”: “######”
}
}
})

headers = {
‘Authorization’: ‘ApiKey cDZHYzlZa0JadVREZDJCendQbXY6SkJlTzNjLV9TRENyQk1RdnFKZGRQdw==’,
‘Content-Type’: ‘application/json’
}

response = requests.request(“POST”, url, headers=headers, data=payload)

print(response.text)

But I’m a little lost on how this workflow will work on Knack. Using GPT I asked to trasnlate this Python code into JavaScript

$(document).on(‘keyup’, ‘#view_74-field_1’, function() {
var numeroProcesso = $(‘#view_74-field_1’).val();

if (numeroProcesso) {
    var apiUrl = 'https://api-publica.datajud.cnj.jus.br/api_publica_trt2/_search';
    
    fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Authorization': 'ApiKey cDZHYzlZa0JadVREZDJCendQbXY6SkJlTzNjLV9TRENyQk1RdnFKZGRQdw==',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            query: {
                match: {
                    numeroProcesso: numeroProcesso
                }
            }
        })
    })
    .then(response => response.json())
    .then(data => {
        // Inserir os dados retornados em campos específicos do formulário
        $('#view_74-field_16').val(data.hits.hits[0]._source.classe.nome);  // Classe Processual
        $('#view_74-field_17').val(data.hits.hits[0]._source.tribunal);  // Tribunal
        $('#view_74-field_102').val(data.hits.hits[0]._source.movimentos.map(mov => mov.nome).join(', '));  // Movimentos
        
        // Atualizar os campos do formulário automaticamente
        Knack.showSpinner();
        Knack.views['view_74'].model.updateView();
    })
    .catch(error => {
        console.error('Erro ao buscar dados do processo:', error);
    });
}

});

But it’s not working. If I add the lawsuit number or update it, knack is not bringing the data. Where am I missing it?

thanks
Lucas

Hi Lucas

Have you logged the value of numeroProcesso to the console, to make sure you have the right value? Another app that we used when we started using the knack API is Postman . In postman you can set up the api and then test it works. It also has the option to convert your API call into javascript.

Happy to try and help more if you need.

Craig

Hey Craig,

thank you for your help!! :slight_smile:

Yes, on Postman API is working fine and bringing all data (Which will be also a second challenge to organize and select all the info it brings).
What I’m missing here is how the JS work.

Once I have updated the numeroProcesso field with the number and save it, JS will run automatically and update the information obtained from API to the proper field?

Hi Lucas

Where you get the response can you console.log the response and then data to make sure that the API is working and you are getting the data in the first place. Once you know this then we can troubleshoot the rest of the JS:

 .then(response => {
        response.json()
        console.log('Response', response);
})(data => {
        console.log('Data', data');
        // Inserir os dados retornados em campos específicos do formulário
        $('#view_74-field_16').val(data.hits.hits[0]._source.classe.nome);  // Classe Processual
        $('#view_74-field_17').val(data.hits.hits[0]._source.tribunal);  // Tribunal
        $('#view_74-field_102').val(data.hits.hits[0]._source.movimentos.map(mov => mov.nome).join(', '));  // Movimentos
        
        // Atualizar os campos do formulário automaticamente
        Knack.showSpinner();
        Knack.views['view_74'].model.updateView();
    })

Craig

I have update the code… reading Knack Docs, I noticed the option to trigger an API call to make a follow-up change to a record only when a certain field is changed. I have also added the console.log, but still, no feedback on console… Im not sure if updating the field is triggering the code.

$(document).on(‘knack-records-render.view_74’, function(event, scene, records) {
// Listener para quando um campo em uma tabela é atualizado (no caso, view_74)
$(document).on(‘knack-cell-update.view_74’, function(event, view, updatedRecord) {

    // Filtra o registro atualizado, comparando com o ID dos registros previamente carregados
    var recordBeforeUpdate = records.filter(recordFromRenderEvent => {
        return recordFromRenderEvent.id === updatedRecord.id;
    })[0];

    // Verifica se o campo field_1 foi alterado
    if (updatedRecord.field_1 !== recordBeforeUpdate.field_1) {
        // Fazer a chamada para a API apenas se o valor do campo field_1 foi modificado
        
        var apiUrl = 'https://api-publica.datajud.cnj.jus.br/api_publica_trt2/_search';

        fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Authorization': 'ApiKey cDZHYzlZa0JadVREZDJCendQbXY6SkJlTzNjLV9TRENyQk1RdnFKZGRQdw==',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                query: {
                    match: {
                        numeroProcesso: updatedRecord.field_1
                    }
                }
            })
        })
        .then(response => {
            console.log('Response:', response);
            return response.json();
        })
        .then(data => {
            console.log('Data:', data);
            // Atualiza os campos no formulário ou na tabela com os novos valores obtidos
            $('#view_74-field_16').val(data.hits.hits[0]._source.classe.nome);  // Classe Processual
            $('#view_74-field_17').val(data.hits.hits[0]._source.tribunal);  // Tribunal
            $('#view_74-field_102').val(data.hits.hits[0]._source.movimentos.map(mov => mov.nome).join(', '));  // Movimentos
            
            // Atualizar os campos do formulário automaticamente
            Knack.showSpinner();
            Knack.views['view_74'].model.updateView();
        })
        .catch(error => {
            console.error('Erro ao buscar dados do processo:', error);
        });
    }

    // Remove o evento para evitar múltiplas execuções
    $(this).off(event);
});

});

On Postman POST worked fine bringing all the data

Where are you trying to run this on a form or a grid?

Form

I thought so. I’ll send you some code that will get the value of an input in the morning with error checking to see if we have the value. Your second batch of code would work for a grid but not a form. You were close with your first bit of code.

We just need to make sure that we have the value for the processor.

Speak tomorrow

Craig

Good Morning Lucas

Can you start by adding this code then share the console logs with me. Before we do any API calls we need to make sure that we have the value processo. For the code to run can you change the value of processo in the form.

// View Render 74 -  > 
$(document).on('knack-view-render.view_74', function (_, { key: viewId }) {
    console.log('Field Length: ', $(`#${viewId}-field_1`).length);
    $(`#${viewId}-field_1`).on('change', function () {
        const numeroProcesso = $(this).val();
        console.log('Value changed to:', numeroProcesso);
    });
});

Are you sure the field Id is field 1?

Craig

I have created a new app, very simple to avoid any other unseen problem.

I have updated the views: pages/scene_1/views/view_3/

Code was updated to

// View Render 3 - >
$(document).on(‘knack-view-render.view_3’, function (, { key: viewId }) {
console.log('Field Length: ', $(#${viewId}-field_17).length);
$(#${viewId}-field_17).on(‘change’, function () {
const numeroProcesso = $(this).val();
console.log(‘Value changed to:’, numeroProcesso);
});
});// View Render 3 - >
$(document).on(‘knack-view-render.view_3’, function (
, { key: viewId }) {
console.log('Field Length: ', $(#${viewId}-field_17).length);
$(#${viewId}-field_17).on(‘change’, function () {
const numeroProcesso = $(this).val();
console.log(‘Value changed to:’, numeroProcesso);
});
});

Console after update

Try this now and screenshot the log after you have entered a number in numeroProcesso:

    // View Render 74 -  > 
$(document).on('knack-view-render.view_74', function (_, { key: viewId }) {
    console.log('Field Length: ', $(`#${viewId} #kn-input-field_17`).length);
    $(`#${viewId} #kn-input-field_17`).on('input', function () {
        const numeroProcesso = $(this).val();
        console.log('Value changed to:', numeroProcesso);
    });
});

And code is ok on JS

Sorry I hadn’t realised the view had changed can you change the view from 74 to 3

And I didnt see it as well… :woozy_face:

Seams that now the code is working:

Ok so we are nearly there 1 more iteration then and I think we will get the ID:

$(document).on('knack-view-render.view_3', function (_, { key: viewId }) {
    console.log('Field Length: ', $(`#${viewId} #kn-input-field_17 input`).length);
    $(`#${viewId} #kn-input-field_17 input`).on('input', function () {
        const numeroProcesso = $(this).val();
        console.log('Value changed to:', numeroProcesso);
    });
});

When you enter the number you should see it logged out.

Craig

JS working fine!

Now we can add the API and check we have the response:

$(document).on('knack-view-render.view_3', function (_, { key: viewId }) {
        console.log('Field Length: ', $(`#${viewId} #kn-input-field_17 input`).length);
        $(`#${viewId} #kn-input-field_17 input`).on('input', function () {
            const numeroProcesso = $(this).val();
            console.log('Value changed to:', numeroProcesso);
            if (numeroProcesso) {
                var apiUrl = 'https://api-publica.datajud.cnj.jus.br/api_publica_trt2/_search';
                
                fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Authorization': 'ApiKey cDZHYzlZa0JadVREZDJCendQbXY6SkJlTzNjLV9TRENyQk1RdnFKZGRQdw==',
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        query: {
                            match: {
                                numeroProcesso: numeroProcesso
                            }
                        }
                    })
                })
                .then(response => {
                    console.log('Response:', response);
                    return response.json();
                });
            }
        });
    });

CORS error. I have searched for this error and seams it´s because it´s a different domain from the origin. But the API is public and many other apps access it in different domains

Hmm not sure. You could try contacting the API provider for help with this. If it works in other app I’m not sure why it wouldn’t work here.

You can make API call from Knack JavaScript.

Searching the web I found the mode: “no-cors”! And we got through it but with no autorization…
fetch(apiUrl, {
mode: “no-cors”,
method: ‘POST’,
headers: {

I think only alternative will have a Proxy… but this will generate extra costs :frowning: