How to test the Restful API?

Asked

Viewed 2,589 times

0

Hello, I am interning and the boy created an AP and ordered me to do the post http methods,delete and etc.. I wonder if it’s correct what I did and his code, and how I do to test it.

config.js

//qualidade
//var urlBO = 'http://Z1T1BRMXVTA56.br.batgen.com:6405';
var urlBO = 'http://10.92.215.128:6405';

//produção
//var urlBO = 'http://10.0.100.64:6405';


var allowed_users = [
    {
    user:   "mATCPT77",
    nome:   "",
    email:  ""
    },
    {
    user:   "matvdbtt",
    nome:   "",
    email:  ""
    },
    {
    user:   "matfimgo",
    nome:   "",
    email:  ""
    },
    {
    user:   "81242726",
    nome:   "",
    email:  ""
    },
    {
    user:   "matvdpms",
    nome:   "",
    email:  ""
    },
    {
    user:   "cipvdbco",
    nome:   "",
    email:  ""
    },
    {
    user:   "81233167",
    nome:   "",
    email:  ""
    },
    {
    user:   "81260372",
    nome:   "",
    email:  ""
    },
    {
    user:   "matvdjpa",
    nome:   "",
    email:  ""
    },
    {
    user:   "81232993",
    nome:   "",
    email:  ""
    }
];

$.ajax({
    type: 'GET',
    url: 'http://10.92.215.128:6405/api/:users/:id',
    contentType:"application/json; charset=utf-8",
    dataType:"json",
    sucess: function(data) {
        console.log("Usuário encontrado", data); // Retorna todos os usuários.
    }
});

$.ajax({
    type: 'POST',
    url: 'http://10.92.215.128:6405/api/:users/:id',
    data: {id: '', user: '', nome: '', email: ''},
    contentType:"application/json; charset=utf-8",
    dataType:"json",
    sucess: function(data) {
        console.log("Usuário criado com sucesso!", data); // O novo usuário é criado com uma nova ID.
    }
});

$.ajax({
    type: 'PUT',
    data: {id: '', user: '', nome: '', email: ''},
    url: 'http://10.92.215.128:6405/api/:users/:id',
    contentType:"application/json; charset=utf-8",
    dataType:"json",
    sucess: function() {
        // Sem data, apenas um código de sucesso (200).
        console.log("Usuário atualizado com sucesso!"); // Atualiza o usuário.
    }
});

$.ajax({
    type: 'DELETE',
    data: {id: '', user: '', nome: '', email: ''},
    url: 'http://10.92.215.128:6405/api/:users/:id',
    contentType:"application/json; charset=utf-8",
    dataType:"json",
    sucess: function() {
        // Sem data, apenas um código de sucesso (200).
        console.log("Usuário deletado com sucesso com sucesso!"); 
    }
});

bo_restful.js

/***********************************************************************************
Gravar a sessão cookie
***********************************************************************************/
    function writeSession(name, value) {
        if (typeof(Storage) !== "undefined")
            localStorage.setItem(name, value);
        else
            window.location.href = "index.html?msg=Seu navegador não suporta 'Web Storage', procure o administrador do sistema.";
    }
/***********************************************************************************
Ler a sessão cookie
***********************************************************************************/
    function readSession(name) {
        if (typeof(Storage) !== "undefined") {
            return localStorage.getItem(name);
        }else{
            window.location.href = "index.html?msg=Seu navegador não suporta 'Web Storage', procure o administrador do sistema.";
            return "";
        }
    }
/***********************************************************************************
Criação do ajax CORS
***********************************************************************************/
    function createCORSRequest(method, url) {
        var xhr = new XMLHttpRequest();
        if ("withCredentials" in xhr) {
            // Check if the XMLHttpRequest object has a "withCredentials" property.
            // "withCredentials" only exists on XMLHTTPRequest2 objects.
            xhr.open(method, url, false);
        } else if (typeof XDomainRequest != "undefined") {
            // Otherwise, check if XDomainRequest.
            // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
            xhr = new XDomainRequest();
            xhr.open(method, url);
        } else {
            // Otherwise, CORS is not supported by the browser.
            xhr = null;
        }
        return xhr;
    }
/***********************************************************************************
LOGIN
***********************************************************************************/
    function doLogon(auth, user, pass){
        //valida se os campos estão preenchidos
        if ((user != "") && (pass != "")) {
            //loading(true);
            if (getObjetoUsers(user) != "" && getObjetoUsers(user) != "undefined" && getObjetoUsers(user) != null){
                var body = '<?xml version="1.0"?><attrs xmlns="http://www.sap.com/rws/bip"><attr name="userName" type="string">'+ 
                            user + '</attr><attr name="password" type="string">' + 
                            pass + '</attr><attr name="auth" type="string" possibilities="secEnterprise,secLDAP,secWinAD">' + auth + '</attr></attrs>';
                var response;
                var logonToken;
                var urlBip = urlBO + "/biprws/logon/long";
                var logon = createCORSRequest('POST', urlBip, false);
                if (!logon) console.log('Cross-Origin Resource Sharing (CORS) not supported', 'error');
                //logon.open('POST', urlBip, false);
                logon.setRequestHeader('X-PINGARUNER', 'pingpong');
                logon.setRequestHeader('Content-Type', 'application/xml');
                logon.setRequestHeader('Accept', 'application/xml');
                logon.send(body);
                if (logon.readyState == 4 && logon.status == 200) {
                    logonToken = logon.getResponseHeader('X-SAP-LogonToken');
                    token = logonToken;
                    logonToken = logonToken.substring(1,logonToken.length-1);
                    logonToken = logonToken.trim();
                    writeSession("logonToken", '"'+logonToken+'"');
                    writeSession("user", user);
                    var timeStamp = +new Date;
                    window.location.href = "wds.html?t=" +new Date;
                } else {
                    if (auth == "secWinAD"){
                        console.log("Tentativa de conectar usando secWinAD falhou: " + logon.responseXML);
                        doLogon("secEnterprise", user, pass);
                    }else{
                        window.location.href = "index.html?msg=Falha na autenticação com o SAP, entre em contato com o administrador do sistema caso este problema se repita (readyState:" + logon.readyState + " status:" + logon.status + ").";
                    }
                }
            }else{
                window.location.href = "index.html?msg=Permissão negada ao usuário '" + user + "'.";
            }
        } else {
              window.location.href = "index.html?msg=As informações de Login e Senha são obrigatórias.";
        }
    }
/***********************************************************************************
LOGOFF
***********************************************************************************/
    function doLogoff(){
        if (confirm("Deseja realmente encerrar sua sessão?")) {
            var token = readSession("logonToken")
            var urlBip = urlBO + "/biprws/logoff";
            var logoff = createCORSRequest('POST', urlBip, false);
            if (!logoff) console.log('Cross-Origin Resource Sharing (CORS) not supported', 'error');
            //logoff.open('POST', urlBip, false);
            logoff.send();
            localStorage.removeItem("user");
            localStorage.removeItem("logonToken");
            window.location.href = "index.html?msg=Sua sessão foi finalizada com sucesso.";
        }
    }

1 answer

2

There are several ways to test Apis, an easy and practical way is to use frameworks and for automated testing to develop scripts.

Postman and Swagger

The Postman and the Swagger are free tools where it is possible to document the API and test it, it is useful because it makes it possible to send Jsons with specific headers just by completing the fields and clicking "Send" without the need for any code and has test history.

To use Swagger, the API developer usually uses the appropriate annotations and the documentation and paths are generated automatically. The link is made available to all developers or publicly (if there are third party applications they can access), usually localhost:8080/path_application/Swagger

Example of API documentation with Swagger

In your case, the developer probably didn’t release the documentation with Swagger so I suggest using Postman.

In Postman, select the type of HTTP Request (GET, POST, PUT etc), add in the Headers tab the corresponding contenttype, in the Body tab select the Raw and JSON(application/json) option and paste your JSON into this field.

Resources

Your API URL is as 10.92.215.128:6405/api/:users/:id and for that piece of code of yours, I believe there may be confusion about Apis.

Resources are implemented as nouns and have their own logic and sometimes even specific database or server (Microservices are there!). Users is a type of Resource and by default REST we have that the URL of your API should be accessed as (or should be in a good Rest API implementation):

/api/users/{id}

In the case {id}, is a type of pathParam and the ID must be passed through the URL.

CURL

Another way that can be useful and commonly found in documentation is to perform tests through the terminal. Example of how to perform a GET request for the User that has ID 1:

curl -i -H "Accept: application/json" "10.92.215.128:6405/api/users/1"

After all, and in the case of your script?

You already have a JS script ready and if you believe it is the most suitable solution, the most useful would be to associate your config.js with some . html page and use the inspector to debug the outputs and returned codes obtained.

Interesting links

What is an Microservices architecture?

Requests for Rest API

When to use @Queryparam vs @Pathparam

Browser other questions tagged

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