Dev.to WebDev 🛠 Dev 👁 2 📖 13 min read

How JavaScript Connects Websites to APIs: A Beginner-Friendly Guide to Fetching and Sending Data

Have you ever opened a weather website and wondered how it knows the current weather conditions? Or visited an online store and watched product information appear on your screen without someone manually adding every det

How JavaScript Connects Websites to APIs: A Beginner-Friendly Guide to Fetching and Sending Data

Have you ever opened a weather website and wondered how it knows the current weather conditions?

Or visited an online store and watched product information appear on your screen without someone manually adding every detail to the webpage?

Perhaps you have logged into an account and immediately seen your profile information, recent activities, or available appointments.

These experiences have something important in common: APIs.

Modern websites do not always work with information stored directly inside their webpages. Many connect to other applications, databases, and online services to retrieve information or send data.

JavaScript plays an important role in making these connections possible.

Through APIs, JavaScript can help websites retrieve product information, display news articles, fetch weather updates, load user profiles, submit forms, and perform many other tasks.

But what exactly is an API? How does JavaScript communicate with one? And what do terms like fetch(), promises, async, and await mean?

Let's break everything down in a simple, practical way.

  1. What Is an API? API stands for Application Programming Interface.

That might sound complicated, but the concept is easier to understand than the name suggests.

An API is a communication interface that allows different software applications or systems to exchange information or request services from one another.

Think about visiting a restaurant.

You sit down and decide what you want to eat. You give your order to a waiter, who communicates your request to the kitchen. The kitchen prepares the food, and the waiter brings it back to you.

You don't need to enter the kitchen yourself or understand how everything works behind the scenes.

The waiter provides a way for you to communicate with the kitchen.

An API works in a similar way.

One application makes a request through an API, another system processes that request, and a response is returned.

For example, imagine building a weather website.

You want visitors to see the current weather in their locations. Instead of building your own weather-monitoring system, you can connect your website to a weather service that provides weather information through an API.

Your website requests the information, receives the response, and displays the relevant details.

In simple terms, an API provides a way for software systems to communicate and exchange information.

  1. How Do Websites Use APIs? APIs are used in many of the websites and applications people interact with every day.

Let's look at some practical examples.
A. Retrieving Product Information
Imagine visiting an online shopping website.

You want to see available shoes, clothing, prices, product descriptions, and images.

Where does this information come from?

In many applications, product information is stored in a database and made available through a backend API.

JavaScript can send a request to that API, receive the product information, and display it on the webpage.

For example, when a user opens a product category, the website can request the available products and display the results.

This means developers don't have to manually write every product into the webpage.
B. Displaying News Articles
Have you ever visited a news website and noticed that new articles appear regularly?

A website can connect to a news service through an API to retrieve available articles.

JavaScript can request the latest headlines, receive the information, and display the articles on the webpage.

The information might include:

  • Article titles.
  • Publication dates.
  • Short descriptions.
  • Images.
  • Article links. This allows the website to display updated information without requiring developers to manually enter every article. C. Fetching Weather Information Consider a weather application.

When you search for a city, the application may retrieve information such as:

  • Current temperature.
  • Weather conditions.
  • Humidity.
  • Wind speed.
  • Weather forecasts. JavaScript can send a request to a weather API, receive the information, and display the results.

For example, a user searches for Lagos, and the website retrieves the corresponding weather information from its connected weather service.
D. Loading User Profiles
When users log into an online platform, they often expect to see their personal account information.

This might include their name, profile picture, account settings, and recent activities.

A website can use an API to request the relevant information from its backend.

JavaScript receives the response and helps display the information in the appropriate sections of the webpage.

Of course, the backend must verify that the user is authorized to access the requested information.
E. Retrieving Available Appointments
Imagine building an appointment-booking website for a hospital, salon, consultant, or other service provider.

Visitors need to see available dates and appointment times before making a booking.

JavaScript can request the latest availability from the booking system through an API.

The website then displays the available options.

When a user selects an appointment, JavaScript can send that selection to the backend for validation and booking.

This helps create a more convenient booking experience.
F. Sending Form Data to a Backend
APIs are not only useful for retrieving information. They can also help websites send information to other systems.

For example, consider a contact form on a business website.

A visitor enters their:

  • Name.
  • Email address.
  • Phone number.
  • Message. When the visitor clicks the submit button, JavaScript can send the form information to a backend API.

The backend can then validate and process the information, perhaps saving it in a database or forwarding it to another service.

This is how many websites handle registrations, enquiries, applications, and other form submissions.

  1. How Does JavaScript Communicate With an API? Now that we understand what APIs do, let's explore how JavaScript communicates with them.

One important JavaScript feature used for this purpose is fetch().
Understanding fetch()
The Fetch API provides a way to make HTTP requests and retrieve resources from a server.

In simpler terms, it allows JavaScript to ask another system for information or send information to it.

For example, imagine you want to retrieve a list of products from an API.

You might write:
fetch("https://example.com/api/products")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Something went wrong:", error);
});

Let's understand what happens here.

Step 1: JavaScript sends a request.
fetch("https://example.com/api/products")

JavaScript sends a request to the specified API endpoint.

An endpoint is a specific URL through which an application can access a particular API resource or operation.

Step 2: The response is received.
.then(response => response.json())

When the server responds, JavaScript processes the response.

The json() method reads the response body and converts JSON data into a JavaScript value.

Step 3: JavaScript works with the returned information.
.then(data => {
console.log(data);
});

The information is now available for JavaScript to work with.

Instead of simply displaying it in the console, a developer can use it to update the webpage.

Step 4: Errors are handled.
.catch(error => {
console.error("Something went wrong:", error);
});

If the request fails because of a network error or another issue that rejects the promise, this section handles the error.

One important detail: fetch() does not automatically reject a promise when a server responds with an HTTP error such as 404 or 500. Developers should also check response.ok to handle unsuccessful HTTP responses properly.

This example uses a placeholder API address. A real project would use an actual API endpoint.

  1. What Are Promises in JavaScript? When JavaScript communicates with an API, the operation may take some time.

The server needs to receive the request, process it, and return a response.

JavaScript does not need to stop everything else while waiting.

This is where Promises become useful.

A Promise is a JavaScript object that represents the eventual result of an operation that may take some time to complete.

Think of ordering food at a restaurant.

You place your order, but the food is not ready immediately.

You receive an indication that your order is being processed. Eventually, the food becomes available, or you may be informed that something went wrong.

A JavaScript Promise works in a similar way.

It can be in one of three states:

  1. Pending: The operation is still in progress.
  2. Fulfilled: The operation completed successfully.
  3. Rejected: The operation failed. When a Promise is fulfilled, JavaScript can work with the returned result.

When it is rejected, JavaScript can handle the error.

This is particularly important when retrieving information from APIs because network requests do not always complete immediately or successfully.

  1. Understanding Async and Await Another important concept in API integration is async and await.

If you have ever looked at JavaScript code containing several .then() statements, you might have wondered whether there is an easier way to write it.

There is!

JavaScript provides async and await to make asynchronous code easier to read and understand.

Let's look at each one.

What does async mean?

The async keyword is used before a function declaration to make that function return a Promise.

For example:
async function getProducts() {
return "Products retrieved!";
}

Even though the function returns a simple string, calling it produces a Promise.

What does await mean?

The await keyword tells JavaScript to wait for a Promise to settle before continuing with the next statement inside the asynchronous function.

For example:
async function getProducts() {
const response = await fetch(
"https://example.com/api/products"
);

const products = await response.json();

console.log(products);
}

Let's break this down.

  • async declares an asynchronous function.
  • fetch() sends a request to the API.
  • await waits for the request's Promise to settle.
  • response.json() reads the returned JSON data.
  • Another await waits for that operation to complete.
  • console.log() displays the resulting data. Notice how this approach makes the code easier to follow.

It reads more like a sequence of instructions, even though the underlying operations are asynchronous.
What About Errors?
Developers also need to prepare for situations where an API request fails.

JavaScript provides try...catch for handling errors when using async and await.

For example:
async function getProducts() {
try {
const response = await fetch(
"https://example.com/api/products"
);

if (!response.ok) {
  throw new Error("Unable to retrieve products");
}

const products = await response.json();

console.log(products);

} catch (error) {
console.error(error.message);
}
}

Here, the try block contains the operations that may fail.

If an error occurs, the catch block handles it.

This makes it easier to build applications that respond appropriately when requests fail.

  1. How Does JavaScript Send Information to an API? So far, we have focused mainly on retrieving information.

But what if a website needs to send information to a server?

For example, imagine a user completing a registration form.

JavaScript can send the submitted information to a backend API using an HTTP request.

One common method is POST.

Consider this example:
async function registerUser() {
try {
const response = await fetch(
"https://example.com/api/register",
{
method: "POST",

    headers: {
      "Content-Type": "application/json"
    },

    body: JSON.stringify({
      name: "Amaka",
      email: "[email protected]"
    })
  }
);

if (!response.ok) {
  throw new Error("Registration failed");
}

const result = await response.json();

console.log(result);

} catch (error) {
console.error(error.message);
}
}

Let's understand some important parts.

  • method: "POST" tells the server that the request is intended to submit information.
  • headers provide additional information about the request.
  • Content-Type: application/json indicates that the request body contains JSON data.
  • JSON.stringify() converts a JavaScript object into a JSON string.
  • body contains the information being submitted. The backend receives the request, processes the submitted information, and returns a response.

In a real registration system, the backend would also validate the information, securely handle passwords, and apply appropriate security measures.

This is one way JavaScript connects the frontend of a website to its backend.

  1. Understanding Common HTTP Methods When working with APIs, you will frequently encounter HTTP methods.

These methods describe the type of operation a client wants to perform.

Here are four common examples:
HTTP Method Common Purpose
GET Retrieve information
POST Submit or create information
PUT Replace an existing resource
DELETE Delete a resource

Another method worth knowing is PATCH, which is commonly used to update part of an existing resource.

For example:

  • GET: Retrieve available products.
  • POST: Submit a new customer registration.
  • PUT: Replace an existing user profile.
  • PATCH: Update a user's email address.
  • DELETE: Remove a product from a system. The exact behaviour depends on how the API is designed.

Understanding these methods will help you read API documentation and communicate with backend services more effectively.

  1. What Is the Difference Between an Internal API and an External API? Not every API a website uses belongs to another company or platform.

APIs can be internal or external.

Internal APIs

These are APIs designed for communication between different parts of an organisation's own software systems.

For example, an e-commerce website might have an internal API that allows its frontend to retrieve product information from its backend.

It could also have separate services for customer accounts, orders, and inventory.

External APIs

These are APIs provided by third-party services that other developers or applications can integrate into their projects.

For example:

  • A weather service providing weather information.
  • A payment provider offering payment processing.
  • A mapping service providing location information.
  • A news service providing article information. A website can integrate these services to offer additional functionality without having to build every feature from scratch.

However, developers must follow the API provider's documentation, access requirements, usage limits, and security guidelines.

  1. Why Is API Integration Important in Modern Web Development? API integration has become an important part of building modern websites and applications.

Here are some reasons why.

  1. Access to External Information

Websites can retrieve useful information from other services instead of maintaining every piece of information themselves.

  1. Better User Experiences

Users can access updated information, submit forms, make payments, and interact with different website features more conveniently.

  1. Easier Integration With Other Services

Developers can connect websites to payment systems, maps, weather services, booking platforms, and many other applications.

  1. More Functional Websites

APIs make it possible to build websites that do more than display static information.

  1. Efficient Development

Developers can use existing services instead of building every functionality from the beginning.

For businesses, this can make it easier to expand their digital services and connect different parts of their operations.

  1. What Should Beginners Learn Before Working With APIs? If you are new to JavaScript and web development, API integration might initially seem complicated.

However, you can learn it gradually.

Here are some concepts worth understanding:

  • HTML: Learn how to structure webpage content.
  • CSS: Understand how to style webpage elements.
  • JavaScript fundamentals: Learn variables, functions, objects, arrays, and conditions.
  • DOM manipulation: Understand how to display information dynamically.
  • Events: Learn how to respond to user actions.
  • JSON: Understand how structured information is represented and exchanged.
  • HTTP basics: Learn how requests, responses, and HTTP methods work.
  • Fetch API: Practise retrieving information from an API.
  • Promises: Understand how JavaScript handles asynchronous operations.
  • Async and Await: Learn how to write readable asynchronous code.
  • Error handling: Understand how to handle failed requests and unexpected responses. Practical Projects to Try The best way to understand API integration is to practise.

Here are some beginner-friendly projects you can build:

  1. Weather Application

Connect to a weather API and display weather information based on a user's selected city.

  1. News Application

Retrieve news articles from an API and display their titles, descriptions, and publication dates.

  1. Product Listing Website

Fetch product information from an API and display the products in an organised layout.

  1. User Profile Application

Retrieve user information from an API and display names, email addresses, and profile details.

  1. Appointment Booking Interface

Retrieve available appointment slots from a backend API and allow users to select their preferred times.

  1. Contact Form

Build a form that sends submitted information to a backend API and displays an appropriate success or error message.

Start with simple projects and gradually introduce more functionality as your understanding improves.

One important security reminder: never expose private API keys, secret credentials, or sensitive authentication tokens in frontend JavaScript. Sensitive operations and protected credentials should be handled securely on the backend.
Conclusion: JavaScript Connects Websites to a Wider Digital World
JavaScript does much more than make buttons clickable or change the appearance of webpage elements.

It also helps websites communicate with other software systems through APIs.

Whether it is retrieving product information, displaying news articles, fetching weather updates, loading user profiles, checking available appointments, or submitting form data, API integration makes many modern website features possible.

Understanding fetch(), promises, async, and await gives you the foundation to start building applications that retrieve and exchange information.

And remember:

An API provides the communication interface between software systems. JavaScript helps your website send requests, receive responses, and work with the information exchanged.

This is an essential part of moving from building simple static webpages to developing more functional, connected, and interactive web applications.

The more you understand how these technologies work together, the more possibilities you unlock as a web developer.

Join the Conversation
Let's hear from developers, aspiring developers, and technology enthusiasts!

If you could integrate one API into a website today, which would you choose?

  1. Weather API – To display weather updates.
  2. Payment API – To process online payments.
  3. News API – To display the latest articles.
  4. Mapping API – To provide location and navigation features.
  5. E-commerce API – To retrieve product information. Share your choice and tell us why in the comments.
📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.