How to call an api with JavaScript

2

I must make a Landingpage , and in this I must include 4 lines of 5 API products.

How do I call that API from JavaScript and how do I just put 4 lines of 5 products?

I have a page that is an API, and that contains some products with categories, product id .... this is what it contains

[  
   {  
      "dataBasic":{  
         "id":"33",
         "productoId":"2646"
      },
      "dataComplete":[  
         {  
            "id":"2646",
            "referencia":"102 -2119",
            "descripcion":"Enterizo Levantacola Capellini",
            "en_descripcion":"Enterizo Levantacola Capellini",
            "es_url":null,
            "en_url":null,
            "marca":"1",
            "precioAlDetal":"89.90",
            "precioPorPaquete":"44.49",
            "precioPorMayor":"44.49",
            "precioTienda":"64.40",
            "precioMiscelaneo":"48.00",
            "precioOutlet":null,
            "proveedor":"2",
            "publicar":"Si",
            "publicarOferta":"Si",
            "publicarEnTienda3":null,
            "publicarEnTienda4":null,
            "publicarEnTienda5":null,
            "descripcion_long_es":null,
            "descripcion_long_en":null,
            "categoriaId":"21",
            "nom_marca":"Capellini",
            "cod_proveedor":"102",
            "nom_proveedor":"CAPOHEIRA"
         }
      ],

What I need is for this data to show me a html con su respectiva imagen and with some styles applied in css.

    
asked by leidy diana arango muñoz 13.06.2017 в 16:53
source

4 answers

2

I use a class API based on JQuery to work with everything related to api . Depending on the api to use the token will have a different operation, in my case my API uses the token by Header of the petición HTTP

    var api; // Variable api global para todos los .js
    class Api {
        // Se usa el constructor para crear nuestra api con la url correcta
        constructor(host, port, protocol, token) {
            this.host = host;
            this.port = port;
            this.protocol = protocol;
            this.token = token;
            this.baseUrl = protocol + host + ":" + port + "/";
            this.result = undefined;
            this.req = undefined;
        };
// Creamos las funciones GET, POST y les asignamos un succes CallOut para recuperar los datos de la peticion
        Get(req, async) {
            this.req = req;
//Creamos una peticion ajax usando jQuery, aqui deberias de crear la petición usando los parámetros que necessites para tu API
                $.ajax({ async: async, type:'get', url: this.baseUrl + req, headers: {
                    "token": this.token
                }, success: successCallOut, error: function(xhr,status,error){
                    console.log("-----------Error Api GET " + this.baseUrl + req + "------------------");
                    console.log("Status: " + status);
                    console.log("Error :" + error);
                    console.log(xhr);
                    console.log("---------------End Error----------------");
                    this.result = "error";
                }});
                if(!async){
                    while (this.result == undefined) {}
                    return this.result;
                }
            };
            GetSync(req){
                return this.Get(req, false);
            };
            GetAsync(req){
                return this.Get(req, true);
            };
            Post(req, body, bodyType, async) {
                this.req = req;
                $.ajax({ async: async, type:'post', url: this.baseUrl + req, data: body, contentType: bodyType, headers: {
                    "token": this.token
                }, success: successCallOut, error: function(xhr,status,error){
                    console.log("-----------Error Api POST " + api.baseUrl + req + "------------------");
                    console.log("Body: \"" + bodyType + "\" " + body);
                    console.log("Status: " + status);
                    console.log("Error: " + error);
                    console.log(xhr);
                    console.log("---------------End Error----------------");
                    this.result = "error";
                }});
                if(!async){
                    while (this.result == undefined) {}
                    return this.result;
                }
            }
            PostJson(req, body, async){
                return this.Post(req, body, "application/json", async);
            }
            PostJsonSync(req, body){
                return this.Post(req, body, "application/json", false);
            }
            PostJsonAsync(req, body){
                return this.Post(req, body, "application/json", true);
            }
            SetToken(req){
                $.ajax({ async: false, type:'get', url: this.baseUrl + req,
                 success: tokenCallOut, error: function(xhr,status,error){
                    console.log("-----------Error Api GET " + this.baseUrl + req + "------------------");
                    console.log("Status: " + status);
                    console.log("Error :" + error);
                    console.log(xhr);
                    console.log("---------------End Error----------------");
                    this.token = "error";
                }});
            }
        };
        function tokenCallOut(data){
            console.log("API TOKEN SUCCESS");
            api.token = data;
        }
        // Aqui es donde trabajaremos con los resultados de la petición, por ejemplo tu haces la peticion a /productos y la redirijes a la funcion ProcesarProductos(), mi ejemplo es /news/last
        function successCallOut(data){
            console.log("API GET/POST SUCCESS");
            api.result = data;
            switch (api.req){
                case "auth":
                    alert(data['token']);
                    break;
                case "handle":
                    alert(data);
                    break;
                case "news/last":
                    ShowLastNews();
                    break;
            }
        };

    function ShowLastNews() {
        //Recuperamos el resultado de la peticion
        var news = api.result;
        //Mostramos el resultado de la petición
        console.log(news);
        //Aqui és donde tienes que hacer los GetElementById() y assignarles el contenido de la petición
    }

More information of AJAX with JQuery link

To work with this class is very easy you just need to call the function GET of the class

<script type="text/javascript">
        window.onload = IndexLoadCode;
        function IndexLoadCode() {
            api = new Api('localhost','3000','http://','');
            api.SetToken('auth?user=main');
            api.GetSync('news/last');
        }
    </script>

Which returns the next result

In my case as the request that returns the api and returns it as JSON I get the object directly as JSON and I do not need the JSON.Parse ()

To add the content to the elements, it's that simple

$(#id).html(api.result.contenido);

You can also add it by creating elements DOM

Create elements of the DOM with jquery

To add css

link

link

To change the image use attr link

$(#img).attr('src',api.result.src);

Extra information on how to work with JSON

Tour JSON with JQuery

How can I traverse a json array and get its values to show them in the view?

I hope you have not left me anything and that it will help you!

    
answered by 30.08.2017 / 11:42
source
0

Well here is a way to do it. Let's imagine that the API returns the following:

{
 'username': 'Einer',
 'profileImg' : 'https://2.bp.blogspot.com/-kdXug2D99gg/V8lWesUS0nI/AAAAAAAADcA/5a2fTm3mTkwwrlO-RpzXM7SZ9ydTSpqzQCLcB/s320/cool-boys-kid-style-whatsapp-dp-profiledp.jpg'
};

We would only have to do the following:

<div id="contenedor">
  </div>
function presentarUsuario()
{
   var responseAPI = {
     'username': 'Einer',
     'profileImg' : 'https://2.bp.blogspot.com/-kdXug2D99gg/V8lWesUS0nI/AAAAAAAADcA/5a2fTm3mTkwwrlO-RpzXM7SZ9ydTSpqzQCLcB/s320/cool-boys-kid-style-whatsapp-dp-profiledp.jpg'
    };

  var info = '<div class="user-info">' +
      '<img src="' + responseAPI.profileImg + '" />' +
  "<div class='username'>" + responseAPI.username + "</div>" +

'</div>';

  document.getElementById("contenedor").innerHTML = info;
}

Here the css:

 .user-info{
    background:white;
    border:solid 1px #ccc;
    box-shadow:0px 0px 2px #ccc;
    cursor:pointer;
    font-size:14px;
    color:#000;
    }

.user-info img{
  width:30px;
  display:inline;
}
.username{
    position: absolute;
    top: 47px;
    font-size: 19px;
  left: 41px;
}
.user-info:hover{
 background:#f9f9f9
}

Example in jsbin .

    
answered by 13.06.2017 в 20:11
0

You can use Ajax to request the API and take the response regardless of the number of items returned.

Here is an example:

$(document).ready(function () {

    jQuery.support.cors = true;

    $.ajax(
     {
         type: "GET",
         url: 'http://myapi:port/',
         data: { get_param: 'name' },
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         cache: false,
         success: function (data) {
             var trHTML = '';
             $.each(data, function (i, element) {
                  trHTML += '<tr><td>' + element.name + '</td><td>';
             });
             /* #product es el nombre de una tabla, pero puedes utilizar cualquier contenedor html*/
             $('#product').append(trHTML);
         },

         error: function (msg) {

             trHTML += msg.responseText;
         }
     });
});
    
answered by 13.06.2017 в 20:23
-1

try this:

    var json = '[{"dataBasic":{"id":"33","productoId":"2646"},"dataComplete":    [{"id":"2646","referencia":"102 -2119","descripcion":"Enterizo Levantacola Capellini","en_descripcion":"Enterizo Levantacola  Capellini","es_url":null,"en_url":null,"marca":"1","precioAlDetal":"89.90","precioPorPaquete":"44.49","precioPorMayor":"44.49","precioTienda":"64.40","precioMiscelaneo":"48.00","precioOutlet":null,"proveedor":"2","publicar":"Si","publicarOferta":"Si","publicarEnTienda3":null,"publicarEnTienda4":null,"publicarEnTienda5":null,"descripcion_long_es":null,"descripcion_long_en":null,"categoriaId":"21","nom_marca":"Capellini","cod_proveedor":"102","nom_proveedor":"CAPOHEIRA"}]}]';

    var obj = JSON.parse(json);
    document.getElementById("prueba").innerHTML = obj[0].dataBasic.id + ", " + obj[0].dataBasic.productoId + ", " + obj[0].dataComplete[0].id + ", " +  obj[0].dataComplete[0].referencia + ", "+ obj[0].dataComplete[0].descripcion;
    <!DOCTYPE html>
    <html>
    <body>
    <p id="prueba"></p>
    </body>
    </html>

Here we read the JSON and then we have it in a label, if there is a lot more data, you must go through it with for o foreach . Afterwards you can build your HTML table with the styles you want.

I hope it serves you.

    
answered by 13.06.2017 в 19:38