Tutorial de como consumir un Web Api REST desde jQuery

Aquí aprenderás a como consumir un web Api REST utilizando Ajax desde jQuery, este tipo de consultas nos facilita bastante a la hora de consumir este tipo de servicios ya que nos permite hacer una consulta de manera asíncrona y sin la necesidad de tener que refrescar toda nuestra web para poder actualizar nuestro contenido.

Para empezar el tutorial deberemos tener a mano la siguiente librería de jQuery agregada en nuestro archivo.

Puedes descargarlas desde jQuery o bien puedes agregar el CDN de la librería:


Vamos a buscar un la pagina JSON Place Holder, para obtener un ejemplo de una estructura json tal como si fuera un web api, al hacer click en el enlace, veremos algo como esto.

    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"

Ya aqui tenemos lo necesario para empezar a trabajar nuestro archivo que consumira nuestro Web Api de ejemplo.

Bien este tipo de archivos debemos de colocarlo en algun ambiente servidor que tengamos disponible, ya sea uno contratado o en nuestra misma computadora, yo en este caso utilizo apache, pueden instalarlo a través de AppServer para que les instale el servicio Apache para el servidor, MySQL y PHP.

Luego de tenerlo instalado, nos dirigimos a la ruta C:\AppServ\www\ y crearemos una carpeta nueva, pueden utilizar el nombre que mas les guste, yo utilizare EjemploWebApi.

Dentro de la carpeta crearemos un archivo HTML, puede ser Index o como gusten.

Abrimos el archivo en nuestro editor de texto avanzado (Utilizo Sublime Text).

Haremos nuestro ezquema HTML tal cual se muestra en la imagen:

<!DOCTYPE html>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<link rel="stylesheet" href="">

<body >
	<table id="tabla" border=1>


Ya luego de tener eso, vamos a crear nuestro script jQuery para poder consultar nuestro WebApi.

Debajo del cierre de nuestro archivo, tenemos un bloque <script></script> abierto, aqui insertaremos el codigo siguiente.

$(document).ready(function () {  
         type: "GET",  
         url: "https://jsonplaceholder.typicode.com/posts/",    
         dataType: "json", 
         success: function (data) {  
               $.each(data, function(i,item){
                     var row = "<tr>"+
                     "<td>" + item.id + "</td>" + 
                     "<td>" + item.title + "</td>" +
                     "<td>" + item.body + "</td>" +
         }, //End of AJAX Success function  

Para empezar nuestro script ajax en jQuery, tan solo debemos de colocar $.ajax({}); dentro de esos corchetes ira nuestra configuración que nos permitirá acceder al web api, la configuración es la siguiente:

TYPE: Aquí vamos a especificar el tipo de request que haremos al servidor o Web Api que vamos a utilizar, en este caso solo estamos utilizando método GET, bien pueden utilizar (GET, POST, DELETE,PUT).

  • GET: lo utilizamos para simplemente obtener datos del Web Api.
  • POST: lo utilizamos para poder enviar datos al Web Api o mejor dicho en caso que queramos insertar algún registro nuevo.
  • DELETE: Se utiliza para indicar al Web Api que estamos requiriendo eliminar un registro.
  • PUT: Con este le indicamos al Web Api que queremos actualizar un registro.

URL: Aquí colocaremos la dirección de nuestro Web Api, al que vamos a acceder, en el ejemplo tiene colocado la dirección que suministre mas arriba de JSON Place Holder.

DATATYPE: Con esto le indicamos a nuestro script el tipo de formato que estaremos recibiendo o consultando, mejor dicho el retorno de nuestro Web Api, en este caso seria “JSON”.

SUCCESS: En esta sección se lanza cuando el script ha completado el request al servidor, utilizamos esta sección para capturar nuestros datos a través de una función, en la que especificamos una variable para capturar nuestro retorno, dentro de la misma función, podemos indicar donde queremos mostrar la data o cualquier evento que vayamos a utilizar, en nuestro ejemplo definimos una estructura para el cuerpo de la tabla.

Como indicamos anteriormente, dentro de la función que agregamos al evento Success, colocamos la variable “data”, la misma, nos servirá para poder capturar los datos que nos devuelve nuestro web api, para obtener los datos en caso de que sea una colección de registros, debemos utilizar un bucle para poder recorrer de manera completa nuestra colección y mostrarla donde queramos.

En el ejemplo que tenemos, utilizamos un bucle “Each”, este tipo de bucle es propio de jQuery.

Trabaja con dos secciones $.each(primea,segunda):

  • En la primera sección la utilizamos para indicarle la variable que vamos a recorrer, en este caso “data”.
  • En la segunda sección le asignamos una función para poder capturar el record de cada registro uno por uno.

Esta función utiliza dos parámetros function(parámetro1,parametro2){},

  • Parametro1: captura la posición de la fila recorrida 0,1,2,3,4,5 etc…
  • Parámetro2: Captura el record de cada fila que el bucle esta recorriendo, para pode acceder a los datos, solo debemos de indicar el nombre de esta variable como se ve en el ejemplo “item” + punto + nombre de la seccion o variable del json que nos retorna el web api, en este caso serian.

Hasta aquí este pequeño tutorial de como consumir un web api rest desde jQuery con Ajax, te dejo un video de mi canal mas abajo explicando este mismo tutorial.

1,434 thoughts to “Tutorial de como consumir un Web Api REST desde jQuery”

  1. Amazing! This blog looks exactly like my old one! It’s on a totally different subject but
    it has pretty much the same page layout and design. Excellent choice of colors!

  2. I was wondering if anyone knows what happened to Dimepiece Los Angeles celebrity streetwear brand? I am having trouble to proceed to the checkout on Dimepiecela site. I have read in GQ that they were acquired by a UK hedge fund for $50 million. I have just bought the Dimepiece Death Metal Weekender Bag from Ebay and totally love it xox

  3. I would like to thank you for the efforts
    you’ve put in writing this website. I’m hoping to view the same high-grade blog posts from you in the future as well.

    In truth, your creative writing abilities has inspired me to get my own website now 😉

  4. Hi there! This post could not be written much better! Reading through this post reminds me of my previous roommate! He constantly kept preaching about this. I’ll forward this information to him. Pretty sure he’ll have a great read. Thanks for sharing!

  5. Hi! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing a few months of hard work due to no back
    up. Do you have any solutions to stop hackers?

  6. I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do
    it for you? Plz answer back as I’m looking to
    create my own blog and would like to know where u got this from.
    appreciate it

  7. I do not even know the way I ended up here, however I believed this publish was once
    good. I don’t recognize who you might be but certainly you are going to a famous blogger in the
    event you aren’t already. Cheers!

  8. First of all I want to say awesome blog! I had a quick question in which I’d like to
    ask if you do not mind. I was interested to know how you center yourself
    and clear your thoughts before writing. I have had trouble clearing my mind in getting my thoughts
    out. I do take pleasure in writing however it just seems like the first 10
    to 15 minutes tend to be wasted simply just trying to
    figure out how to begin. Any ideas or tips? Many thanks!

  9. Remarkable issues here. I am very satisfied to peer your article.
    Thank you a lot and I’m looking ahead to contact you.
    Will you kindly drop me a e-mail?

  10. I’m not that much of a internet reader to be honest but your sites really nice,
    keep it up! I’ll go ahead and bookmark your website to come back in the future.

  11. Hi, I do think this is a great site. I stumbledupon it 😉 I’m going to revisit once again since I bookmarked it.
    Money and freedom is the best way to change, may you be rich and continue to guide other people.

  12. It’s appropriate time to make some plans for the long run and it’s
    time to be happy. I have read this post and if I may I desire to suggest you few attention-grabbing issues or advice.
    Maybe you can write subsequent articles referring to
    this article. I wish to read more things about it!

  13. It is the best time to make some plans for the future and it is time to be happy.
    I have read this post and if I could I desire to
    suggest you few interesting things or suggestions.
    Maybe you could write next articles referring to this article.
    I want to read even more things about it!

  14. Woah! I’m really loving the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s challenging to get
    that “perfect balance” between user friendliness and visual
    appearance. I must say that you’ve done a superb job with this.
    Also, the blog loads extremely quick for me on Safari.
    Excellent Blog!

  15. I’ve been surfing online more than three hours today, yet I by no means discovered any
    fascinating article like yours. It’s beautiful value sufficient for
    me. In my opinion, if all site owners and bloggers made excellent content material as you
    probably did, the net will be much more helpful than ever before.

  16. My brother suggested I might like this blog. He was totally right.
    This post actually made my day. You cann’t imagine just
    how much time I had spent for this information! Thanks!

  17. Thanks for your helpful post. Through the years, I have come to be able to understand that the symptoms of mesothelioma cancer are caused by the build up of fluid regarding the lining of the lung and the chest muscles cavity. The illness may start from the chest place and spread to other parts of the body. Other symptoms of pleural mesothelioma cancer include fat loss, severe breathing trouble, vomiting, difficulty ingesting, and puffiness of the face and neck areas. It should be noted that some people existing with the disease usually do not experience almost any serious indications at all.

  18. Hi there, this weekend is nice designed for me, for the reason that this occasion i am reading this
    enormous informative paragraph here at my home.

  19. Does anyone know whether I can purchase Just Delta 8 Cartridges (justdeltastore.com) from Vapor J’s, 48 West Bridge Street, Oswego, NY, 13126?

  20. [url=https://ngcialis.com/]cialis cost in india[/url] [url=https://sildenafilhot.com/]cheap sildenafil[/url] [url=https://buyrealcialis.com/]cheap cialis no prescription[/url] [url=https://onlinenorx.com/]plaquenil uk[/url] [url=https://longpills.com/]cephalexin 100mg price[/url] [url=https://gettadalafil.com/]generic tadalafil coupon[/url]