← ← Back to all posts

What is an API and how do you use it?

2025-11-06 · Benja

You will learn how to use APIs correctly and securely.

What is an API and how do you use it?

What Is an API?Guide with Real Examples

APIs (Application Programming Interfaces) are the backbone of modern software. They allow applications, services, and devices to communicate with each other — sharing data or functionality without exposing internal structures. This guide explains, with practical examples and real code, how APIs work and why they are essential to today’s digital world.


Part 1: What Is an API? The Restaurant Analogy

Imagine you walk into a restaurant.

  • You are an application (a client).
  • The menu is the API documentation.
  • The waiter is the API (Application Programming Interface).
  • The kitchen is the server (the system that holds the data or functionality).

How does it work?

  1. You make a Request: You read the menu (documentation) and tell the waiter (API) what you want: “A burger with fries.”
  2. The API processes it: The waiter takes your order to the kitchen (server). He knows how to talk to the cooks and in what format.
  3. You get a Response: The kitchen prepares the food, and the waiter (API) brings it to you. You don’t see the mess inside — you just get the final result.

Technical Definition: An API is an intermediary that allows two software systems to communicate with each other, following defined rules and protocols.


// Conceptual example
// Client -> API -> Server
// Request: "Give me the weather data"
// Response: { temperature: 22, city: "Madrid" }
  

Part 2: Types of APIs (By Accessibility)

APIs can be classified according to who can access them:

API Type Who Can Use It? Purpose Example
Public API (Open) Any developer Expand the ecosystem and promote external innovation Twitter API, Google Maps API, Spotify API
Private API (Internal) Developers inside a company Connect internal systems and improve efficiency An API linking sales with inventory
Partner API Authorized business partners Strategic integration between companies Airline API used by a travel booking site

Part 3: API Architecture Styles (How They Communicate)

1. REST (Representational State Transfer)

REST is the most widely used architecture. It relies on standard HTTP verbs to act on resources. Each request is independent (stateless), and data is usually exchanged in JSON format.


GET /users         // Get all users
GET /users/123     // Get user with ID 123
POST /users        // Create a new user
PUT /users/123     // Update user 123
DELETE /users/123  // Delete user 123
  

2. SOAP (Simple Object Access Protocol)

SOAP is a formal, XML-based protocol ideal for enterprise and financial systems that need high reliability and security.

3. GraphQL

Created by Facebook, GraphQL lets clients request exactly the data they need — no more, no less — in a single request. This eliminates over-fetching and under-fetching.


{
  user(id: "123") {
    name
    email
    posts(limit: 5) {
      title
    }
  }
}
  

This query retrieves the user’s name, email, and titles of their last five posts in one call.


Part 4: Real-World Examples You Use Every Day

  • Weather Apps: They use REST APIs like OpenWeatherMap to show live forecasts.
  • Login with Google/Facebook: These rely on OAuth APIs that handle authentication securely.
  • Online Payments: Stores use Stripe or PayPal APIs to process transactions safely.
  • Map Integration: Real estate or delivery websites embed Google Maps API.
  • Discord or Telegram Bots: These use public APIs to read and respond to messages.

Part 5: Building a Professional API Handler

Developers often need to manage timeouts, errors, and pagination when consuming APIs. Here’s a modern JavaScript class designed for that purpose:


class APIHandler {
  constructor(baseURL, timeout = 8000) {
    this.baseURL = baseURL;
    this.timeout = timeout;
  }

  async request(endpoint, options = {}) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.timeout);
    
    const config = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      signal: controller.signal,
      ...options
    };

    try {
      const response = await fetch(`${this.baseURL}${endpoint}`, config);
      clearTimeout(timeoutId);
      return await this._processResponse(response);
    } catch (error) {
      clearTimeout(timeoutId);
      return this._handleError(error);
    }
  }

  async _processResponse(response) {
    const contentType = response.headers.get('content-type');
    
    if (!response.ok) {
      throw new Error(`HTTP Error: ${response.status} - ${response.statusText}`);
    }

    if (contentType && contentType.includes('application/json')) {
      return await response.json();
    } else {
      return await response.text();
    }
  }

  _handleError(error) {
    if (error.name === 'AbortError') {
      throw new Error('Timeout: The request took too long');
    } else if (error.name === 'TypeError') {
      throw new Error('Network Error: Could not connect to the server');
    } else {
      throw error;
    }
  }

  async getPaginatedData(endpoint, page = 1, limit = 10) {
    const data = await this.request(
      `${endpoint}?page=${page}&limit=${limit}`
    );
    
    return {
      items: data.items,
      pagination: {
        currentPage: page,
        totalPages: Math.ceil(data.total / limit),
        totalItems: data.total,
        hasNext: page < Math.ceil(data.total / limit),
        hasPrevious: page > 1
      }
    };
  }
}

// Example usage
const weatherAPI = new APIHandler('https://api.openweathermap.org/data/2.5');

weatherAPI.getPaginatedData('/forecast', 2, 5)
  .then(result => {
    console.log('Data:', result.items);
    console.log('Pagination info:', result.pagination);
  })
  .catch(error => {
    console.error('Handled error:', error.message);
  });
  

This handler abstracts all network logic, allowing developers to focus on core business logic instead of repetitive boilerplate.


Part 6: Consolidating Data from Multiple APIs

In e-commerce or logistics, it’s common to merge data from multiple suppliers. The following example shows how to do this efficiently:


class InventoryManager {
  constructor() {
    this.suppliers = {
      supplierA: 'https://api.supplierA.com/inventory',
      supplierB: 'https://api.supplierB.com/stock'
    };
  }

  async checkAvailability(productId) {
    const availability = [];
    
    const requests = Object.entries(this.suppliers).map(
      async ([name, url]) => {
        try {
          const response = await fetch(`${url}/${productId}`);
          const data = await response.json();
          
          availability.push({
            supplier: name,
            stock: data.stock,
            price: data.price,
            deliveryTime: data.delivery_time
          });
        } catch (error) {
          console.error(`Error with ${name}:`, error);
        }
      }
    );
    
    await Promise.all(requests);
    return availability;
  }
}

// Practical usage
const manager = new InventoryManager();
manager.checkAvailability('PROD-123')
  .then(result => {
    console.log('Consolidated availability:', result);
  });
  

Conclusion and Call to Action

APIs are the building blocks of the modern Internet. They connect services, automate processes, and drive continuous innovation. From social networks to financial systems, everything depends on well-designed APIs.

In upcoming articles, we’ll explore:

  • How to make your first REST API call with JavaScript.
  • REST vs GraphQL: Which one should you choose?
  • API Security: How to protect your endpoints.

Author: Benja — NewsBM Tech