Consuming Public APIs in JavaScript Without Axios or jQuery

Consuming Public APIs in JavaScript Without Axios or jQuery

Consuming Public APIs in JavaScript Without Axios or jQuery

 

Modern JavaScript gives us a powerful native tool to make HTTP requests: the Fetch API. Unlike older approaches that relied on jQuery’s AJAX method or third-party tools like Axios, Fetch provides a cleaner, promise-based way to interact with web APIs directly from the browser. In this tutorial, we’ll walk through fetching weather data from a public API, handling errors gracefully, and dynamically displaying the results on a webpage—all without external libraries.

1. Introducing the Fetch API

The Fetch API is a modern replacement for XMLHttpRequest. It uses promises and provides a more powerful and flexible feature set for making HTTP requests directly from JavaScript. Let’s review the basic syntax:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Fetch error:', error));

This simple pattern is what we’ll build upon. Note how the Fetch API returns a promise that resolves whether a request fails at the network level or not. It’s our responsibility to check if the response was successful (usually with response.ok).

2. Choose a Public Weather API

For this example, we’ll use the OpenWeatherMap API. First, sign up at OpenWeatherMap and obtain a free API key. Use the https://api.openweathermap.org/data/2.5/weather endpoint to fetch weather by city name, like so:

const apiKey = 'YOUR_API_KEY';
const city = 'London';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;

You’ll need this URL to make your Fetch call in the next step. Don’t forget to replace YOUR_API_KEY with your actual key.

3. Fetching Weather Data in JavaScript

Now, let’s write some JavaScript that will fetch data from this API and display it on the browser:

async function fetchWeather(city) {
  const apiKey = 'YOUR_API_KEY';
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

  try {
    const response = await fetch(url);

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    displayWeather(data);

  } catch (error) {
    console.error('Error fetching weather data:', error);
    alert('Could not retrieve weather data. Please try again later.');
  }
}

This asynchronous function fetches weather data and passes it to displayWeather() if successful. We also handle HTTP errors and network issues, ensuring a better user experience with meaningful feedback.

4. Dynamically Displaying Weather Data

Here’s how you can dynamically render that data into your HTML:

function displayWeather(data) {
  const output = document.getElementById('weather-output');
  output.innerHTML = `
    <h3>Weather in ${data.name}</h3>
    <p>Temperature: ${data.main.temp} °C</p>
    <p>Condition: ${data.weather[0].description}</p>
    <p>Humidity: ${data.main.humidity}%</p>
    <p>Wind: ${data.wind.speed} m/s</p>
  `;
}

Make sure your HTML includes an element with id="weather-output" for this to work:

<div id="weather-output"></div>

If you’d like to allow users to search for cities, simply add an input and button:

<input id="city-input" placeholder="Enter city" />
<button onclick="handleSearch()">Get Weather</button>
function handleSearch() {
  const city = document.getElementById('city-input').value;
  if (city) {
    fetchWeather(city);
  }
}

5. Best Practices and Optimization Tips

Here are several tips for improving your implementation:

  • Debounce Form Inputs: If you build an auto-search feature, use debounce to avoid making an API call on every keystroke.
  • Loading Indicators: Show a spinner or message while data is loading to improve UX.
  • Throttle API Requests: Most APIs have rate limits; ensure you don’t exceed them by caching data or controlling request frequency.
  • Environment Variables: Store your API key securely. In production, expose it through a server-side proxy or environment config.
  • Weather Icons: Enhance your UI using OpenWeather’s icon codes (e.g., https://openweathermap.org/img/wn/${iconCode}@2x.png).

Example of icon usage inside displayWeather:

const iconCode = data.weather[0].icon;
const iconUrl = `https://openweathermap.org/img/wn/${iconCode}@2x.png`;
output.innerHTML += `<img src="${iconUrl}" alt="Weather icon" />`;

Conclusion

Using the native Fetch API in JavaScript is a lightweight and highly capable solution for consuming public APIs. Not only does it reduce your dependency on libraries, but it also encourages cleaner asynchronous code using async/await. By integrating real-time weather updates into your projects, you’re also adding practical value for users using a performant and modern stack.

Remember to always validate inputs, handle failures gracefully, and optimize your calls. With just a few lines of native JavaScript, you’ve built a small weather dashboard—no Axios or jQuery required!

 

Useful links: