25 of the best JavaScript APIs
Enhance your sites by making the most of the newest and best JavaScript APIs.
Here's our pick of the best JavaScript APIs around right now, plus a guide to getting started using them. These will help you add new and interesting functionality to your sites and apps. A word of warning: many of these APIs are still in development, so make sure you check browser support before you start using them, and provide fallbacks where necessary.
For more awesome plugins to explore, take a look at our guides to the best HTML APIs and Google APIs, or to build a site from scratch (without code) use a website builder. You might also want to see our guide to some of the best JavaScript frameworks and JavaScript tools to try. Don't forget it's also vital to consider your choice of web hosting service, to make sure your site runs as you want it to.
01. Modify browser settings
- Read more: Mozilla summary
While the browser usually is 'above' any code running in it, a Mozilla-derived API allows JavaScript limited access to browser settings. Think about aspects such as reading the user's homepage, how bookmarks are handled, and where new tabs show up.
02. File APIs
- Read more: W3C summary
Handling large amounts of persistent data always was a bit of a problem for web apps. The W3C file API combines some of the concepts used by various vendors — please do keep in mind that full filesystem access is usually not granted, mostly for security reasons.
03. Microsoft Cognitive services
- Read more: Microsoft summary
Artificial intelligence requires extreme amounts of training data — logically, vendors are not motivated to provide these models to their customers. Instead, developers are allowed to send payloads to a server, which is then analysed on-line.
While all of the large cloud vendors offer more or less sophisticated artificial intelligence services, Microsoft stands out by its focus on AI features. The API offers are subsumed under the term cognitive services; you can access features such as advanced image recognition services. For example, the snapshot accompanying this box shows the AI being used to recognize Microsoft's CEO from a press photo — other features are related to video, handwriting and sound recognition and transcription.
While the quality of output usually is very high, do keep in mind that continued usage is all but cheap — as time goes by, usage charges can and do add up. (If you have media files to back up, use the best cloud storage.)
Get the Creative Bloq Newsletter
Daily design news, reviews, how-tos and more, as picked by the editors.
04. Open Government APIs
- Read more: Data.gov summary
Democratically elected representatives usually show great skill at transforming money. The concept of open government means that the results of these works are made available via (usually open) APIs, allowing third-party developers to perform all kinds of data harvesting magic.
One especially interesting area concerns transportation: public transport services tend to provide APIs with live locations of their vehicles and the frequencies seen on the route network.
This is not done out of pure altruism: when done right, a "local traffic" application for a specific city or town can quickly climb the ranks of the local app store. The government does not need to invest resources into the creation of the service, while the developer — usually — makes a neat buck selling ad space due to the locally limited audience.
In addition to these APIs, developers are also usually let loose on other things. The French government, for example, will provide relatively detailed capabilities for looking up addresses.
05. HERE mapping API
- Read more: HERE summary
Competition, by definition, is good. Here is Nokia's former mapping division, and offers developers a "third party" alternative to the mapping services by the big three. One interesting aspect is the extremely simple API, which makes downloading tiles a breeze.
06. OpenStreetMap API
- Read more: MapBox summary
OpenStreetMap does not provide ready-to-display maps. Instead, a rendering service, such as CartoType, will be needed. When working on a website, creating a dedicated rendering system is a bit of work — MapBox provides a convenient pay-per-use alternative.
07. Master of linguistics
- Read more: Microsoft reference
Programs dealing with user-generated content can score brownie points by offering an integrated translation service. A client for Twitter or Gab could, for example, translate English texts to Russian to make them easier to handle for that audience.
While "machine-based translation systems" are among the oldest research fields in IT, developing a workable machine translator by hand is difficult. Microsoft's Translation API recently was updated to version 3.0, and is a one-stop shop for all problems of babelese scope. In addition to performing translations between language pairs, the service can also be used to find out which language a specific text is in. You can then use this data to configure lesser APIs such as the spell checker.
Finally, idioms and individual words can also be sent into a dictionary query. The information returned is situation dependent — in some cases, Microsoft can even return dozens of idioms to help understanding.
08. Off-screen canvas API
- Read more: Google reference
Developers once used a technique called double buffering to render graphics without flickering. Google has introduced something similar — it creates an off screen window where graphics can be "staged" at high performance.
09. NASA
- Read more: NASA summary
Microsoft's decision to provide Windows Phone 7 users with an occasional curated wallpaper drove ripples through the industry. Given that pictures of Space are always popular, why not go right to the source and grab yourself a few from the never-ending store of NASA?
10. Get Slack data
- Read more: Slack summary
Slack established itself as the go-to tool for "modern project management". Should you ever feel like using data contained in such a project, get yourself an API token and hack away. When done right, your web application can even integrate itself into the Slack GUI.
11. YouTube API
- Read more: Google summary
A YouTube channel is only as good as the analytics which stand behind it. Google's YouTube Data API might not be particularly spiffy, but does provide — among other things — valuable insights into your audience's behaviour.
12. Payment Request API
- Read more: W3C summary
The first JavaScript API we're looking at is the Payment Request API. When creating an ecommerce website, lots of thought goes into improving the checkout flow to make sure the experience is as smooth and pain-free as possible. Entering payment details remains a repetitive process. If any field is slightly wrong, the whole process breaks and it needs to be started again. On the developer’s side, making sure the right validation checks are in place for each payment method is a time-consuming process.
The Payment Request API does away with this part of the checkout experience. The page can request the information it needs and the browser provides the user with the fields to enter.
The user only needs to enter their details once, and they can be used across different websites and transactions. Depending on the device, they can even use the payment methods linked to the user account, such as Google and Apple Pay.
const request = new PaymentRequest(
[{ supportedMethods: "basic-card" }],
{
total: {
label: "Total",
amount: { currency: "GBP",
value: 6.5 }
}
}
);
The object takes a few parameters that describe the payment that should take place. The first details the payment methods accepted. These can be different types of payment cards, as well as details for integrating with other third-party payment solutions. There is even scope to include another web application as a payment method by using the Payment Handler API.
The second is a breakdown of what is being purchased. This can be in any format that makes sense to the transaction. This also includes options for shipping costs, which can be calculated based on other factors, such as delivery address. There is also a third, optional argument to specify any extra information that needs to be collected, such as an email address or contact number.
13. CSS Layout API
- Read more: W3C summary
As a general rule, your website layout should be left down to CSS. With JavaScript, handling changes to layout is prone to poor performance and lots of manual upkeep. But what happens if a site requires a non-standard layout? The traditional grid-like placement that CSS provides may not work for more creative design ideas.
The Layout API enables developers to create their own layout modules, much like the existing grid or flex modules in use today. By defining the rules it should work to, the API can place items anywhere within its containing element. It is the second Houdini API to make it to browsers.
Houdini introduced the concept of ‘worklets’, which work similar to web workers but are highly specialised in one activity. The Layout API works through a specific layout worklet. These get registered with the browser, which enables them to be picked up in CSS.
class MasonryWorklet {
*layout(children, edges, constraints,
styleMap) {}
}
registerLayout("masonry", MasonryWorklet);
A layout worklet has one method called layout, which deals with the positioning of elements. It runs as a generator function, enabling it to run in parallel to the rest of the page to keep everything running smoothly.
The first parameter is a reference to the immediate child elements of the one the layout is applied to. Size data is available from the second and third parameters. One provides position and dimension information about the element being styled, with the other defining the constraints the element has to work within. The final parameter describes the rest of the styles of the element, including any custom properties it may be interested in.
.el {
display: layout(masonry);
}
A custom module is applied by using the usual display property on an element. It uses the layout function, along with the name of the worklet.
14. Credential Management API
- Read more: W3C summary
Instead of having to remember lots of individual login details, users can log in with the credentials stored within the browser. That way, users on multiple devices can have their details follow them around without needing to log in each time.
While a browser’s autocomplete feature may reduce the friction with entering the password itself, the Credential Management API can automatically log a user in as soon as they hit the page. It can also log in using other forms of authentication, such as a public key or through an authentication provider like OpenID.
15. CSS Paint API
- Read more: W3C guide or Google Developers summary
CSS and JavaScript are often seen as separate parts of a website – only ever coming together in small ways, such as adding a class name. Developers have few opportunities to change how the browser decides to render a page other than directly updating the DOM.
That is all set to change in the next year as a new set of specifications start to land in browsers. They provide access to the render pipeline in the browser through JavaScript, to help developers finely tune the browser’s actions to their needs.
The Houdini task force is comprised of a collection of people from browser and technology companies. They have the aim of opening up the way everything renders in the browser in a way that makes it readily approachable for developers. This includes layouts, fonts and animations.
The first specification already hitting browsers is the CSS Paint API (also known as CSS Custom Paint). This API enables you to programmatically generate an image whenever a CSS property expects one. Use JavaScript to generate dynamic backgrounds, borders and image masks and apply them in CSS without a heavy performance hit. It's about to be enabled by default in Chrome Stable.
class MyPaintWorklet {
static get inputProperties() {
return [];
}
paint(ctx, size, properties) {
}
}
registerPaint('my-paint',
MyPaintWorklet);
The Paint API uses a paint worklet to define what the browser should do each time it needs to update the screen. Each paint can use a new version of the worklet, which means that any persistent data should be stored elsewhere.
The paint callback method gets passed three values. The first is the context, which works much like a canvas context. It can be drawn upon in the same way and has most of the same capabilities, but as this can be called multiple times a second it should be kept simple.
The second value provides information about the element being painted, such as its height and width. This can be used to make sure the end result fits perfectly each time it gets used.
The final value contains all the style properties on the object. This includes any input custom properties defined within the getter. These use the Typed Object Model – another new Houdini feature that makes CSS values easier to digest in JavaScript.
The last call registers the worklet with the browser and opens it up to the CSS side.
.el {
background-image: paint(my-paint);
}
To use within CSS, it involves a one-line function. The passed value is the name of the effect provided when registering the worklet. The API and its associated worklet is available in Chrome and Opera, while it remains a key focus for Safari, Firefox and Samsung Internet browsers. While the specification is nearing completion, expect to see it hit those browsers soon.
Later iterations on the specification provide a mechanism for supplying arguments against the CSS function, similar to how gradients are currently defined. This enables easier customisation without having to apply custom properties. Other options, such as defining an alpha channel for layering, are also being considered.
16. Web Animations API
- Read more: W3C guide
Animation with JavaScript has historically had a bad rap. Moving elements by changing position values causes lots of repaints and results in poor performance. CSS animations are the better choice, but they are hard to manipulate on the fly.
The Web Animations API provides access to the same animation engine that powers the CSS side.
Const animation = el.animate(
[
{ transform: "rotate(0)" },
{ transform: "rotate(360deg)" }
],
1000
);
Every element has an animate method, which takes a series of keyframes plus either a settings object or a duration. This returns an animation object, which can then be updated to play, pause and adjust the playback speed.
There is added benefit coming from Houdini, with animation worklets. These work on a similar syntax to the API, but allow for finer control. They can be controlled by inputs other than time, such as scroll or touch position. This is still in development – to find out more, head over to the Chrome developer blog.
Support for the Web Animations API itself is small but is quickly growing. By using feature detection, those who have support for it can feel the benefits straight away.
17. Writable Files API
The long-term goal of web applications is to get them to be on the same level as their native counterparts. Some functionality, however, remains lacking – particularly around managing local files.
Writing files currently involves creating a download and saving to a specific directory. Saving iterations over a specific file will create multiple copies, which is not always a good experience.
The Writable Files API will provide developers with more flexibility and enable users to decide where files should be stored. This opens the door to more fully featured projects on the web, such as an online code editor or complex graphics applications.
This API is currently part of Google’s capabilities project. It’s currently in the process of gathering feedback on potential features before it hits the browser in an origin trial. Issues around security, and what kind of files can be written where, need to be ironed out before the API can be made official.
18. Generic Sensor API
- Read more: W3C guide
The sensors on the devices we carry around every day are a great way of providing extra benefit to an application. Using the physical environment, such as with an accelerometer, can provide added immersion for creative experience.
If we already have events for these kinds of things, why is there a new API? Devices are constantly changing and adding new and varied sensors. To save having to create new APIs for each new sensor that comes out, the Generic Sensor API creates a simplified interface for them all.
While the API is still in development, Chrome and Firefox both include it behind flags to play around with. Other browsers have it under consideration for the future.
19. Paint Timing API
- Read more: W3C guide
Performance is a big focus this year. Getting file sizes down can help, but there is more to performance than what gets downloaded to the browser. The browser ‘paints’ its contents onscreen every time something changes. Until that first paint happens, users will be left staring at a blank screen. When it gets hung up in other details, such as downloading assets or processing JavaScript, the time to that first paint can take longer.
The Paint Timing API keeps detailed information on two events – the first paint and the first ‘contentful’ paint, which refers to something more than just styling, such as text or an image.
The PerformanceObserver interface describes what to do when these events occur. This can then be used to send the data to a server for analysis later on.
Right now, this is only available in Chrome and Opera, but other browsers such as Edge and Safari have both shown an interest and will possibly include it in the future.
20. Web Speech API
- Try a demo
- Read more: W3C guide
This API is made of two parts – synthesis and recognition. Speech synthesis will take text supplied to it and read it out in the voice chosen by the user. The SpeechSynthesis object provides access to all the different options, including what it should say. Recognition involves taking a microphone input and understanding the words being said. The SpeechRecognition object is used to detect the speech, which will fire a ‘result’ with what it thinks the user said and how confident it is.
The synthesis side of the API is supported in all major browsers. Speech recognition support is currently limited to Chrome with a prefix, or Firefox with a flag enabled.
There are discussions to expand the recognition side to include other inputs, including WebRTC to provide real-time transcripts of video conferencing. While these are still in the early stages, it could help make webinars and online presentations more accessible and easier to reference in the future.
21. Intersection Observer
- Read more: W3C summary
This JavaScript API can be used to understand the visibility and position of DOM elements (known as 'targets') relative to a containing element (the 'root'). Use it to fire a callback whenever an element enters and exits a certain area. This API is best for lazy loading or infinite scroll effects.
22. Reporting Observer
- Read more: W3C summary
Part of the Reporting API, Reporting Observers observe some types of reports from JavaScript. Use them to get notified when the browser has to intervene – for example, if it has to provide a fallback for a slow-loading font.
23. OffscreenCanvas
- Read more: Google Developers summary
Drawing to a <canvas> is an expensive task for a browser. This new API enables you to render graphics off the main thread, without hitting the DOM.
24. Internationalisation API
- Read more: MDN web docs
Known by the namespace Intl, the ECMAScript Internationalization API provides language-sensitive string comparison, number formatting, and date and time formatting. Use it to avoid sending heavy libraries and show dates, numbers and strings in a format that makes sense in the user’s location.
25. GraphQL
- Read more: GraphQL
While this is not an API in the strictest sense, GraphQL is something that always deserves a mention when it comes to discussing APIs.
The method to the madness relates to queries running against servers containing an object store. Instead of forcing developers to create an access API for each and every element, a "generic" query language is established. The developer of an API must then provide a standardised description of the objects contained within:
type Query {
me: User
}
type User {
id: ID
name: String
}
In the next step, fire off one or more queries against these formalised descriptions. An example against a (fictional) human database would look like this:
{
human(id: "1000") {
name
height
}
}
GraphQL capable servers react by returning a JSON object containing the wanted fields. Due to space constraints, we can not elaborate this topic further – this tutorial does, however, provide an interesting overview.
This is an edited version of articles that originally appeared in Web Designer magazine.
Read more:
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
Matt Crouch is a front end developer who uses his knowledge of React, GraphQL and Styled Components to build online platforms for award-winning startups across the UK. He has written a range of articles and tutorials for net and Web Designer magazines covering the latest and greatest web development tools and technologies.