APIs are everywhere on the Internet, and knowing how to interact with them is an important skill for the modern web developer. Being able to access and interact with third-party data can take your apps to the next level in lots of cool ways!

In this article, we’re going to take a look at some of the best APIs that developers can access and how APILayer makes it easy to do so.

We created this article in partnership with APILayer. Thank you for supporting the partners who make SitePoint possible.

What’s an API?

API stands for application programming interface, and it can describe anything that allows two programs to communicate with each other. For example, methods such as document.insertNode aren’t actually part of JavaScript: they’re a part of the DOM API that allows your program to communicate with the DOM.

Web APIs allow your code to communicate and interact with websites and online services in a controlled way. In most cases, this is done by sending a request that returns some data, which is almost always in JSON format. This data can then be used in your code.

Many APIs also allow you to offload some of the workload from your application to an external service. For example, if you wanted to translate a document, you could avoid having to write all the code for doing this this and instead use an API.

APILayer

APILayer is a curated API marketplace. Every API is carefully selected by APILayer’s team of developers to ensure that it’s secure and stable, with the ability to scale as your site grows. All the APIs have a free plan, and you don’t need to hand over any payment details to get started. APILayer currently features almost 100 APIs, with more being added all the time. These APIs cover a range of categories, from finance to food, as well as featuring a number of web development tools such as image processing and spell checking.

Each API has different payment tiers, starting from free and increasing in price depending on you how many requests you’ll be making. Some of the paid plans might also offer a greater variety of data to be requested as well. APILayer makes it easy to sign up for an API you find interesting and offers a live demo feature that lets you test out how the API works directly in your browser, as well as providing some sample code to get you started. It also features full documentation and reviews for each API.

Interacting with an API

The easiest way to interact with APIs via JavaScript is to use fetch. This asynchronously requests data from a URL and returns a promise that allows us to access the data that’s returned.

Let’s have a look at a simple example:

fetch("https://geek-jokes.sameerkumar.website/api?format=json")
  .then(response => response.json())
  .then(result => console.log(result.joke))
  .catch(error => console.log('error', error.message))

This code will request data from the Geek Jokes API, which returns a random joke in JSON format. We pass the API URL to the fetch function. This returns a promise, and we can chain the then method to it — first of all, to convert the JSON that’s returned into a JavaScript object using the json() method, and then to simply log the joke property of this object to the console. We also add a catch block to the end to log any errors.

Fetch requests accept a second parameter where you can specify any options for the request, including headers. A fairly standard set of options is shown below:

const headers = new Headers()

const requestOptions = {
  method: 'GET',
  redirect: 'follow',
  headers
}

These can then be added to the request:

fetch("https://geek-jokes.sameerkumar.website/api?format=json", requestOptions)
  .then(response => response.json())
  .then(result => console.log(result.joke))
  .catch(error => console.log('error', error.message))

Most services will require a key to be provided in order to grant access to the API. This can be included as part of the headers or in the URL.

It’s immensely important to keep your API keys hidden. Typically, they should be stored and encrypted on a server. This is to prevent them from being visible in the source code and used by somebody else. This is usually more of an issue when you’re paying the company for a subscription, as the company wouldn’t want to give away free access to their code.

Six of the Best

Let’s take a look at six of the best APIs that developers can access on APILayer. Please note that for all the examples below, you’ll have to change the access key (the API key) to match your own.

Spotify

The Spotify API is one of the biggest (and coolest) APIs available on APILayer. It allows you access to a load of music and podcast data that’s available on Spotify.

Using this API, you can get data such as albums, album tracks, artists, artist albums, playlists, tracks and track lyrics. This means you can search for an artist and receive information about all their published work/albums, including when it was released and the credited writers and musicians.

Here’s an example that returns all the albums of a given artist:

const headers = new Headers()
headers.append("apikey", "YOUR_API_KEY")

const getAlbums = event => {
  event.preventDefault()
  const requestOptions = {
    method: 'GET',
    redirect: 'follow',
    headers
  }
  fetch("https://api.apilayer.com/spotify/search?q=" + encodeURIComponent(event.target.artist.value), requestOptions)
    .then(response => response.json())
    .then(result => {document.getElementById("albums").innerHTML = result.albums.items.map(x => `<li>${x.data.name}</li>`).join``})
    .catch(error => console.log(error.message))
}

document.getElementById("music").addEventListener("submit", getAlbums)

World News

The World News API gives you access to thousands of news sources from all over the world. The results come from a variety of news outlets, meaning you can get the same news story from a variety of viewpoints.

The API also returns a vast amount of data, including the title, byline, author and summary of each news story, as well as any pictures that are available. The API allows you to search for stories by date and location, meaning you can get up-to-the-minute news as well as historic stories from a particular locale. The language and country of origin can also be specified in the search. There’s also a nifty AI feature that classifies stories as being either “positive” or “negative”, allowing you to curate the stories that are returned even further.

Here’s an example that returns the top five news stories from today:

const headers = new Headers()
headers.append("apikey", "YOUR_API_KEY")

const requestOptions = {
  method: 'GET',
  redirect: 'follow',
  headers
}

const today = new Date()
const date = `${today.getFullYear()}-${today.getMonth()+1}-${String(today.getDate()).padStart(2,'0')}`

fetch(`https://api.apilayer.com/world_news/search-news?number=5&language=en&earliest-publish-date=${date}`, requestOptions)
  .then(response => response.json())
  .then(result => render(result))
  .catch(error => console.log('error', error))

const render = data => document.getElementById("news").innerHTML = data.news.map(story => `<h2>${story.title}</h2><img src=${story.image}/><section>${story.summary}</section>`).join``

Weatherstack

The Weatherstack API allows you to access the current and historical weather statistics for any given location, from anywhere in the world. The current feature gives you access to real-time weather statistics, such as temperature, wind direction, pressure and visibility.

There’s a huge amount of data to be accessed here, particularly in the historical weather feature that dates back to July 2008, meaning you can obtain the weather stats for any place from any date after July 2008. The place and date need to be specified as parameters. The historical feature also has an optional “hourly” parameter which can be set to 1 or 0, depending on whether or not you want the weather data split hourly. If you choose to split the data hourly, you can also set an optional parameter of “interval” to 1, 3 (default), 6, 12 or 24, depending on how you want the data to be split.

Both historical and current features have an optional “units” parameter, where you can set the units of the data to be “m” for Metric, “f” for Fahrenheit or “s” for Scientific.

Here’s an example of code that returns the current temperature of a given location:

const getWeather = event => {
  event.preventDefault()
  const requestOptions = {
    method: 'GET',
    redirect: 'follow',
  }
    fetch("https://api.weatherstack.com/current?access_key=YOUR_API_KEY&query="+encodeURIComponent(event.target.city.value), requestOptions)
    .then(response => response.json())
    .then(result => document.getElementById("weather").innerHTML = `<h1>The current temperature in ${result.location.name} is ${result.current.temperature}</h1>`)
    .catch(error => console.log(error.message))
}

document.getElementById("place").addEventListener("submit", getWeather)

Number Verification

The Number Verification API allows you to look up phone numbers from over 200 countries and verify their authenticity. The API will also return details about the country, country code, mobile carrier and line type (mobile or landline). This will allow you to verify a phone number provided by a user of your web app in real time.

Below is an example that lets you enter a phone number into a form. Submitting the form will return whether or not the number is valid. If it’s valid, it will also display the country the phone number is based in:

const headers = new Headers()
headers.append("apikey", "YOUR_API_KEY")

const verify = event => {
  event.preventDefault()
  const requestOptions = {
    method: 'GET',
    redirect: 'follow',
    headers
  }
  fetch(`https://api.apilayer.com/number_verification/validate?number=${event.target.number.value}`, requestOptions)
  .then(response => response.json())
  .then(result => render(result))
  .catch(error => console.log('error', error.message))
}

document.getElementById("phone").addEventListener("submit",verify)

const render = data => document.getElementById("verification").textContent = data.valid ? `This is a valid phone number from ${data.country_name}` : `This is not a valid phone number`

Zenserp

The Zenserp API is a SERP (search engine results page) API that allows you to scrape the search engine results pages in a much cleaner object format. Its endpoints include Google, Image Reverse Search, YouTube, Bing and DuckDuckGo. The Google endpoint also includes sub-endpoints of Image, Maps, Video, News and Shopping. Results also include ranking information that will help you identify popular pages and trends.

There are also some List Endpoints that can be used for making your own request generation. These include: Google languages, Google countries, Geo Locations and Google Search Engines.

Given a search item, the API will return all the pages that would appear, including its URL and description.

Here’s an example that will return the top Google search for a topic:

const headers = new Headers()

const serp = event => {
  event.preventDefault()
  const requestOptions = {
    method: 'GET',
    redirect: 'follow',
    headers
  }
  fetch(`https://app.zenserp.com/api/v2/search?apikey=YOUR_API_KEY&q=${encodeURIComponent(event.target.q.value)}`, requestOptions)
  .then(response => response.json())
  .then(result => render(result))
  .catch(error => console.log('error', error.message))
}

document.getElementById("search").addEventListener("submit",serp)

const render = data => document.getElementById("result").innerHTML = `The top search result on Google is: <a href="${data.organic[0].url}"><h1>${data.organic[0].title}</h1></a><p>${data.organic[0].description}</p>`

Zenscrape

The Zenscrape API is a web scraping API that, for its basic usage, will return the HTML content of any given website. For this, you only need to provide one parameter — the URL of the target website — and the API key. It will also generate any dynamic HTML on the page from any JavaScript or frontend framework such as React or Vue. This means that the returned HTML will be the same content that a user would see.

At first, this may not seem like something you’d need to use. But web scraping — and therefore this API — can be really useful for interacting and analyzing statistics. For example, you could use this API to create an app that compared prices for a product on multiple different sites and showed the user the shopping site that offered the best value for that product.

The API also provides an HTTP proxy interface. An HTTP proxy is a high-performace content filter that filters all web traffic, flagging any suspicious content that may be a virus or intrusive and unwanted data. The interface allows you to use any application that already relies on proxies, you simply need to use the API key as a username and include any parameters normally supplied as the password.

This also allows you to specify a specific proxy location to get specific geolocation based content returned. The proxy that’s used also gets automatically rotated to help keep the scraping bot anonymous and stop sites from limiting the number of times you can scrape them.

Here’s an example that lets you enter a URL and that will return the HTML to the console:

const headers = new Headers()

const scrape = event => {
  event.preventDefault()
  const requestOptions = {
    method: 'GET',
    redirect: 'follow',
    headers
  }
  fetch(`https://api.allorigins.win/get?url=${encodeURIComponent(`https://app.zenscrape.com/api/v1/get?apikey=YOUR_API_KEY&url=${encodeURIComponent(event.target.url.value)}`)}`,requestOptions)
  .then(response => response.json())
  .then(result => console.log(result.contents))
  .catch(error => console.log('error', error.message))
}

document.getElementById("scrape").addEventListener("submit",scrape)

Conclusion

These six examples only scratch the surface of what APILayer has to offer. There are lots more APIs available, so make sure you explore the site fully and have fun with some of them. For example, we highly recommend the Bad Words API, which we both had a lot of fun messing around with!



Source link

Translate »