How to test the Restful API?

0
Hello, I'm practicing and the boy created an AP and told me to do the http methods of post, delete and etc ... I would like to know if it is correct what I did and the code of it, and how I do it for the 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.";
        }
    }
    
asked by anonymous 07.04.2017 / 15:34

1 answer

2

There are several ways to perform API tests, an easy and practical way is to use frameworks and automated testing to develop scripts.

Postman and Swagger

The Postman and the Swagger are free tools where you can document the API and test it, it is useful because it allows you to send JSONs with specific headers just by completing the fields and clicking" Send "without the need of any code and have historical of tests.

To use Swagger, the API developer often 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 / my_application / swagger

API documentation example with Swagger

In your case, probably the developer did not make the documentation available with Swagger so I suggest using Postman.

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

Resources

Your API URL is like 10.92.215.128:6405/api/:users/:id and for that code snippet, I think there might be a mixup about APIs.

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

/ api / users / {id}

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

CURL

Another way that can be useful and commonly found in documentation is to conduct 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, what about your script?

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

Interesting links

What is an architecture of microservices?

Requests for API Rest

When to use @QueryParam vs @PathParam

    
07.04.2017 / 20:44