Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

En primer lugar empezaremos mirando las APIS desde un nivel alto — qué son, cómo funcionan, cómo usarlas en el código, y cómo están estructuradas. También echaremos un vistazo a cuáles son los principales tipos de APIs, y para qué se usan.

Prerrequisitos: Conocimientos básicos de informática, principios básicos de HTML, CSS y JavaScript (ver primeros pasos, bloques de construcción, objetos JavaScript).
Objetivo: Familiarizarse con las APIs, saber qué pueden hacer y cómo usarlas en tu código.

¿Qué son las APIs?

Las Interfaces de programacion de aplicaciones son construcciones disponibles en los lenguajes de programación que permiten a los desarrolladores crear funcionalidades complejas de una manera simple.

Como ejemplo, piensa en el suministro de electricidad de tu casa, apartamento, o cualquier otro lado. Si quieres usar un electrodoméstico, simplemente lo conectas en un enchufe y funciona. No intentas conectarlo directamente a la fuente de alimentación — hacerlo sería muy ineficiente y, si no eres electricista, dificil y peligroso.

Fuente de la imagen: Overloaded plug socket por The Clear Communication People, en Flickr.

De la misma manera, se puede decir, es mucho más fácil programar gráficos 3D usando una API escrita en un lenguaje de alto nivel como JavaScript o Python, en lugar de intentar escribir directamente código de bajo nivel (C o C++) que controle directamente la GPU de la computadora u otras funciones gráficas.

Nota: Consulta también la entrada API del glosario para una descripción más detallada.

APIs en JavaScript del lado cliente

JavaScript del lado cliente, particularmente, tiene muchas APIs disponibles — no son parte del lenguaje en sí, sino que están construidas sobre su núcleo, proporcionándote superpoderes adicionales para usar en tu código. Por lo general, se dividen en dos categorías:

  • Las APIs de navegador están integradas en tu navegador web y pueden exponer datos del navegador y del entorno informático circundante y hacer cosas complejas y útiles con él. Por ejemplo, la API de Geolocalización proporciona algunas construcciones simples de JavaScript para obtener datos de ubicación con los que, por ejemplo, trazar tu ubicación en un mapa de Google. En segundo plano, el navegador está usando en realidad algún complejo código de bajo nivel (por ejemplo, C++) para comunicarse con el hardware GPS del dispositivo (o lo que esté disponible para determinar los datos de posición), recuperar los datos de posición y devolverlos al entorno del navegador para su uso en tu código Pero, una vez más, la API abstrae esta complejidad.
  • Las APIs de terceros no están incluídas por defecto en el navegador, y por lo general tienes que obtener el código e información desde algún lugar de la Web.  Por ejemplo, la API de Twitter te permite hacer cosas como mostrar tus últimos tweets en tu sitio web. Proporciona un conjunto especial de construcciones que puedes usar para consultar el servicio de Twitter y devolver información específica.

 

 

 

Relacion entre JavaScript, APIs, y otras herramientas de JavaScript

Así que, más arriba, hablamos sobre qué son las APIs de JavaScript del lado cliente y cómo se relacionan con el lenguaje. Recapitulemos ahora para dejarlo claro, y veamos también dónde encajan otras herramientas de JavaScript:

  • JavaScript — Un lenguaje de scripts de alto nivel incorporado en los navegadores que permite implementar interactividad en páginas web / apps. Ten en cuenta que JavaScript también está disponible en otros entornos de programación, como Node.
  • APIs de navegador — construcciones integradas en el navegador creadas con el lenguaje JavaScript y que permiten implementar funcionalidad mucho más fácilmente.
  • APIs de terceros — construcciones integradas en plataformas de terceros (por ejemplo Twitter, Facebook) que permiten usar algunas de las funcionalidades de esa plataforma en tus páginas web (como por ejemplo mostrar tus últimos Tweets en tu página web).
  • Librerías JavaScript — Por lo general uno o más archivos JavaScript que contienen funciones personalizadas que puedes añadir a tu página web para acelerar o habilitar la escritura de funcionalidad común. Por ejemplo jQuery, Mootools y React.
  • Frameworks JavaScript — El siguiente paso a las librerías, los frameworks JavaScript (como Angular y Ember) suelen ser paquetes de HTML, CSS, JavaScript y otras tecnologías que se instalan y luego se usan para escribir una aplicación web completa desde cero. La diferencia clave entre una librería y un framework es la "Inversión del control". Cuando se llama a un método desde una librería, el desarrollador tiene el control. Con un framework el control se invierte: el framework llama al código del desarrollador.

¿Qué pueden hacer las APIs?

Hay una gran cantidad de APIs disponibles en los navegadores modernos que te permiten hacer una gran variedad de cosas en tu código. Puedes verlo echando un vistazo al índice de APIs de MDN.

APIs de navegador más comunes

En particular, las categorías más comunes de APIs de navegador más usadas (y que trataremos con mayor detalle en este módulo) son:

  • APIs para manipular documentos cargados en el navegador. El ejemplo más obvio es la API DOM (Document Object Model), que permite manipular HTML y CSS — crear, eliminar y modificar HTML, aplicar estilos dinámicos a una página, etc. Cada vez que se muestra una ventana emergente en una página, o un nuevo contenido, por ejemplo, es el DOM en acción. Más información sobre este tipo de APIs en Manipulando documentos.
  • APIs that fetch data from the server to update small sections of a webpage on their own are very commonly used. This seemingly small detail has had a huge impact on the performance and behaviour of sites — if you just need to update a stock listing or list of available new stories, doing it instantly without having to reload the whole entire page from the server can make the site or app feel much more responsive and "snappy". APIs that make this possible include XMLHttpRequest and the Fetch API. You may also come across the term Ajax, which describes this technique. Find out more about such APIs in Fetching data from the server.
  • APIs for drawing and manipulating graphics are now widely supported in browsers — the most popular ones are Canvas and WebGL, which allow you to programmatically update the pixel data contained in an HTML <canvas> element to create 2D and 3D scenes. For example, you might draw shapes such as rectangles or circles, import an image onto the canvas, and apply a filter to it such as sepia or grayscale using the Canvas API, or create a complex 3D scene with lighting and textures using WebGL. Such APIs are often combined with APIs for creating animation loops (such as window.requestAnimationFrame()) and others to make constantly updating scenes like cartoons and games.
  • Audio and Video APIs like HTMLMediaElement, the Web Audio API, and WebRTC allow you to do really interesting things with multimedia such as creating custom UI controls for playing audio and video, displaying text tracks like captions and subtitles along with your videos, grabbing video from your web camera to be manipulated via a canvas (see above) or displayed on someone else's computer in a web conference, or adding effects to audio tracks (such as gain, distortion, panning, etc).
  • Device APIs are basically APIs for manipulating and retrieving data from modern device hardware in a way that is useful for web apps. We've already talked about the Geolocation API accessing the device's location data so you can plot your position on a map. Other examples include telling the user that a useful update is available on a web app via system notifications (see the Notifications API) or vibration hardware (see the Vibration API).
  • Client-side storage APIs are becoming a lot more widespread in web browsers — the ability to store data on the client-side is very useful if you want to create an app that will save its state between page loads, and perhaps even work when the device is offline. There are a number of options available, e.g. simple name/value storage with the Web Storage API, and more complex tabular data storage with the IndexedDB API.

Common third-party APIs

Third party APIs come in a large variety; some of the more popular ones that you are likely to make use of sooner or later are:

  • The Twitter API, which allows you to do things like displaying your latest tweets on your website.
  • The Google Maps API allows you to do all sorts of things with maps on your web pages (funnily enough, it also powers Google Maps). This is now an entire suite of APIs, which handle a wide variety of tasks, as evidenced by the Google Maps API Picker.
  • The Facebook suite of APIs enables you to use various parts of the Facebook ecosystem to benefit your app, for example by providing app login using Facebook login, accepting in-app payments, rolling out targetted ad campaigns, etc.
  • The YouTube API, which allows you to embed YouTube videos on your site, search YouTube, build playlists, and more.
  • The Twilio API, which provides a framework for building voice and video call functionality into your app, sending SMS/MMS from your apps, and more.

Note: You can find information on a lot more 3rd party APIs at the Programmable Web API directory.

How do APIs work?

Different JavaScript APIs work in slightly different ways, but generally, they have common features and similar themes to how they work.

They are based on objects

APIs are interacted with in your code using one or more JavaScript objects, which serve as containers for the data the API uses (contained in object properties), and the functionality the API makes available (contained in object methods).

Note: If you are not already familiar with how objects work, you should go back and work through our JavaScript objects module before continuing.

Let's return to the example of the Geolocation API — this is a very simple API that consists of a few simple objects:

  • Geolocation, which contains three methods for controlling the retrieval of geodata.
  • Position, which represents the position of a device at a given time — this contains a Coordinates object that contains the actual position information, plus a timestamp representing the given time.
  • Coordinates, which contains a whole lot of useful data on the device position, including latitude and longitude, altitude, velocity and direction of movement, and more.

So how do these objects interact? If you look at our maps-example.html example (see it live also), you'll see the following code:

navigator.geolocation.getCurrentPosition(function(position) {
  var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    disableDefaultUI: true
  }
  var map = new google.maps.Map(document.querySelector("#map_canvas"), myOptions);
});

Note: When you first load up the above example, you should be given a dialog box asking if you are happy to share your location with this application (see the They have additional security mechanisms where appropriate section later in the article). You need to agree to this to be able to plot your location on the map. If you still can't see the map, you may need to set your permissions manually; you can do this in various ways depending on what browser you are using; for example in Firefox go to > Tools > Page Info > Permissions, then change the setting for Share Location; in Chrome go to Settings > Privacy > Show advanced settings > Content settings then change the settings for Location.

We first want to use the Geolocation.getCurrentPosition() method to return the current location of our device. The browser's Geolocation object is accessed by calling the Navigator.geolocation property, so we start off by using

navigator.geolocation.getCurrentPosition(function(position) { ... });

This is equivalent to doing something like

var myGeo = navigator.geolocation;
myGeo.getCurrentPosition(function(position) { ... });

But we can use the dot syntax to chain our property/method access together, reducing the number of lines we have to write.

The Geolocation.getCurrentPosition() method only has a single mandatory parameter, which is an anonymous function that will run when the device's current position has been successfully retrieved. This function itself has a parameter, which contains a Position object representing the current position data.

Note: A function that is taken by another function as an argument is called a callback function.

This pattern of invoking a function only when an operation has been completed is very common in JavaScript APIs — making sure one operation has completed before trying to use the data the operation returns in another operation. These are called asynchronous operations. Because getting the device's current position relies on an external component (the device's GPS or other geolocation hardware), we can't guarantee that it will be done in time to just immediately use the data it returns. Therefore, something like this wouldn't work:

var position = navigator.geolocation.getCurrentPosition();
var myLatitude = position.coords.latitude;

If the first line had not yet returned its result, the second line would throw an error, because the position data would not yet be available. For this reason, APIs involving asynchronous operations are designed to use callback functions, or the more modern system of Promises, which were made available in ECMAScript 6 and are widely used in newer APIs.

We are combining the Geolocation API with a third party API — the Google Maps API — which we are using to plot the location returned by getCurrentPosition() on a Google Map. We make this API available on our page by linking to it — you'll find this line in the HTML:

<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyDDuGt0E5IEGkcE6ZfrKfUtE9Ko_de66pA"></script>

To use the API, we first create a LatLng object instance using the google.maps.LatLng() constructor, which takes our geolocated Coordinates.latitude and Coordinates.longitude values as parameters:

var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

This object is itself set as the value of the center property of an options object that we've called myOptions. We then create an object instance to represent our map by calling the google.maps.Map() constructor, passing it two parameters — a reference to the <div> element we want to render the map on (with an ID of map_canvas), and the options object we defined just above it.

var myOptions = {
  zoom: 8,
  center: latlng,
  mapTypeId: google.maps.MapTypeId.TERRAIN,
  disableDefaultUI: true
}

var map = new google.maps.Map(document.querySelector("#map_canvas"), myOptions);

With this done, our map now renders.

This last block of code highlights two common patterns you'll see across many APIs. First of all, API objects commonly contain constructors, which are invoked to create instances of those objects that you'll use to write your program. Second, API objects often have several options available that can be tweaked to get the exact environment you want for your program. API constructors commonly accept options objects as parameters, which is where you'd set such options.

Note: Don't worry if you don't understand all the details of this example immediately. We'll cover using third party APIs in a lot more detail in a future article.

They have recognizable entry points

When using an API, you should make sure you know where the entry point is for the API. In The Geolocation API, this is pretty simple — it is the Navigator.geolocation property, which returns the browser's Geolocation object that all the useful geolocation methods are available inside.

The Document Object Model (DOM) API has an even simpler entry point — its features tend to be found hanging off the Document object, or an instance of an HTML element that you want to affect in some way, for example:

var em = document.createElement('em'); // create a new em element
var para = document.querySelector('p'); // reference an existing p element
em.textContent = 'Hello there!'; // give em some text content
para.appendChild(em); // embed em inside para

Other APIs have slightly more complex entry points, often involving creating a specific context for the API code to be written in. For example, the Canvas API's context object is created by getting a reference to the <canvas> element you want to draw on, and then calling its HTMLCanvasElement.getContext() method:

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

Anything that we want to do to the canvas is then achieved by calling properties and methods of the content object (which is an instance of CanvasRenderingContext2D), for example:

Ball.prototype.draw = function() {
  ctx.beginPath();
  ctx.fillStyle = this.color;
  ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
  ctx.fill();
};

Note: You can see this code in action in our bouncing balls demo (see it running live also).

They use events to handle changes in state

We already discussed events earlier on in the course, in our Introduction to events article — this article looks in detail at what client-side web events are and how they are used in your code. If you are not already familiar with how client-side web API events work, you should go and read this article first before continuing.

Some web APIs contain no events, but some contain a number of events. The handler properties that allow us to run functions when events fire are generally listed in our reference material in separate "Event handlers" sections. As a simple example, instances of the XMLHttpRequest object (each one represents an HTTP request to the server to retrieve a new resource of some kind) have a number of events available on them, for example the load event is fired when a response has been successfully returned containing the requested resource, and it is now available.

The following code provides a simple example of how this would be used:

var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();

request.onload = function() {
  var superHeroes = request.response;
  populateHeader(superHeroes);
  showHeroes(superHeroes);
}

Note: You can see this code in action in our ajax.html example (see it live also).

The first five lines specify the location of resource we want to fetch, create a new instance of a request object using the XMLHttpRequest() constructor, open an HTTP GET request to retrieve the specified resource, specify that the response should be sent in JSON format, then send the request.

The onload handler function then specifies what we do with the response. We know the response will be successfully returned and available after the load event has required (unless an error occurred), so we save the response containing the returned JSON in the superHeroes variable, then pass it to two different functions for further processing.

They have additional security mechanisms where appropriate

WebAPI features are subject to the same security considerations as JavaScript and other web technologies (for example same-origin policy), but they sometimes have additional security mechanisms in place. For example, some of the more modern WebAPIs will only work on pages served over HTTPS due to them transmitting potentially sensitive data (examples include Service Workers and Push).

In addition, some WebAPIs request permission to be enabled from the user once calls to them are made in your code. As an example, you may have noticed a dialog like the following when loading up our earlier Geolocation example:

The Notifications API asks for permission in a similar fashion:

These permission prompts are given to users for security — if they weren't in place, then sites could start secretly tracking your location without you knowing it, or spamming you with a lot of annoying notifications.

Summary

At this point, you should have a good idea of what APIs are, how they work, and what you can do with them in your JavaScript code. You are probably excited to start actually doing some fun things with specific APIs, so let's go! Next up, we'll look at manipulating documents with the Document Object Model (DOM).

In this module

Etiquetas y colaboradores del documento

Colaboradores en esta página: robottitto, OrlandoDeJesusCuxinYama
Última actualización por: robottitto,