Yandex Metrika
All Guides
Intermediate

JavaScript Integration

Integrate Echoes API into your JavaScript projects.

JavaScriptIntegration

JavaScript Integration

This guide will show you step-by-step how to integrate the Echoes API into your JavaScript projects. You'll learn the fundamental techniques for using the API in your web applications, Node.js projects, or other JavaScript environments.

Basic Fetch Request

The simplest way to interact with the API in JavaScript is using the `fetch` API:

JavaScript
// Simple fetch request to get a random quote
fetch('https://echoes.soferity.com/api/quotes/random')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log('Quote:', data.quote);
    console.log('Author:', data.author);
  })
  .catch(error => {
    console.error('Error fetching API:', error);
  });

Using Async/Await

In modern JavaScript, you can make requests cleaner and more readable using the `async/await` syntax:

JavaScript
async function getRandomQuote() {
  try {
    const response = await fetch('https://echoes.soferity.com/api/quotes/random');
    
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching quote:', error);
    return null;
  }
}

// Using the function
getRandomQuote()
  .then(quote => {
    if (quote) {
      console.log('Quote:', quote.quote);
      console.log('Author:', quote.author);
    }
  });

Integration with HTML Page

Here's an example of a simple HTML page that displays random quotes from the API:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Echoes Quote Viewer</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .quote-container {
      background-color: #f5f5f5;
      border-left: 4px solid #333;
      padding: 15px;
      border-radius: 4px;
      margin-bottom: 20px;
    }
    .quote-text {
      font-size: 18px;
      font-style: italic;
      margin-bottom: 10px;
    }
    .quote-author {
      font-weight: bold;
      text-align: right;
    }
    button {
      background-color: #4CAF50;
      color: white;
      border: none;
      padding: 10px 15px;
      cursor: pointer;
      border-radius: 4px;
    }
    button:hover {
      background-color: #45a049;
    }
  </style>
</head>
<body>
  <h1>Quote of the Day</h1>
  
  <div class="quote-container">
    <div id="quote-text" class="quote-text">Loading quote...</div>
    <div id="quote-author" class="quote-author"></div>
  </div>
  
  <button id="new-quote-btn">New Quote</button>
  
  <script>
    // Select DOM elements
    const quoteTextElement = document.getElementById('quote-text');
    const quoteAuthorElement = document.getElementById('quote-author');
    const newQuoteButton = document.getElementById('new-quote-btn');
    
    // Function to fetch a random quote
    async function fetchRandomQuote() {
      try {
        // Set elements to loading state
        quoteTextElement.textContent = 'Loading quote...';
        quoteAuthorElement.textContent = '';
        
        // Fetch data from API
        const response = await fetch('https://echoes.soferity.com/api/quotes/random');
        
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        
        const data = await response.json();
        
        // Display the quote
        quoteTextElement.textContent = data.quote;
        quoteAuthorElement.textContent = '— ' + data.author;
      } catch (error) {
        console.error('Error fetching quote:', error);
        quoteTextElement.textContent = 'An error occurred while loading the quote. Please try again.';
      }
    }
    
    // Fetch initial quote when page loads
    fetchRandomQuote();
    
    // Fetch new quote when button is clicked
    newQuoteButton.addEventListener('click', fetchRandomQuote);
  </script>
</body>
</html>

Working with Parameters

To send requests to the API with specific parameters, you can append URL parameters like this:

JavaScript
// Get a random quote in a specific language
async function getRandomQuoteByLanguage(lang) {
  try {
    const url = `https://echoes.soferity.com/api/quotes/random?lang=${lang}`;
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    
    return await response.json();
  } catch (error) {
    console.error('Error fetching quote:', error);
    return null;
  }
}

// Get an English quote
getRandomQuoteByLanguage('en')
  .then(quote => {
    if (quote) {
      console.log('English Quote:', quote.quote);
      console.log('Author:', quote.author);
    }
  });

Error Handling and Retry Mechanism

For a robust application, it's important to add error handling and retry mechanisms to API requests:

JavaScript
async function fetchWithRetry(url, options = {}, retries = 3, backoff = 300) {
  try {
    const response = await fetch(url, options);
    
    if (response.ok) {
      return await response.json();
    }
    
    if (retries > 0) {
      console.log(`Retrying... Attempts left: ${retries}`);
      await new Promise(resolve => setTimeout(resolve, backoff));
      return fetchWithRetry(url, options, retries - 1, backoff * 2);
    }
    
    throw new Error(`HTTP Error: ${response.status}`);
    
  } catch (error) {
    if (retries > 0) {
      console.log(`Connection error, retrying... Attempts left: ${retries}`);
      await new Promise(resolve => setTimeout(resolve, backoff));
      return fetchWithRetry(url, options, retries - 1, backoff * 2);
    }
    throw error;
  }
}

// Use with retry mechanism
fetchWithRetry('https://echoes.soferity.com/api/quotes/random')
  .then(data => console.log('Successfully fetched:', data))
  .catch(error => console.error('All retries failed:', error));

Advanced: Custom Quote Client

For larger applications, it's useful to create a class that wraps the Echoes API:

JavaScript
class EchoesClient {
  constructor(baseUrl = 'https://echoes.soferity.com/api') {
    this.baseUrl = baseUrl;
  }
  
  async getRandomQuote(params = {}) {
    return this._fetch('/quotes/random', params);
  }
  
  async getQuoteById(id) {
    return this._fetch(`/quotes/${id}`);
  }
  
  async getAllQuotes(page = 1, perPage = 10) {
    return this._fetch('/quotes', { page, perPage });
  }
  
  async getRandomQuoteByLanguage(lang) {
    return this._fetch('/quotes/random', { lang });
  }
  
  async getRandomQuoteByAuthor(author) {
    return this._fetch('/quotes/random', { author });
  }
  
  async _fetch(endpoint, params = {}) {
    const url = new URL(`${this.baseUrl}${endpoint}`);
    
    // Add parameters to URL
    Object.keys(params).forEach(key => 
      url.searchParams.append(key, params[key])
    );
    
    try {
      const response = await fetch(url);
      
      if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status}`);
      }
      
      return await response.json();
    } catch (error) {
      console.error('API request failed:', error);
      throw error;
    }
  }
}

// Using the client
const echoesClient = new EchoesClient();

// Get a random quote
echoesClient.getRandomQuote()
  .then(quote => console.log('Random Quote:', quote))
  .catch(error => console.error('Error:', error));

// Get a random quote in a specific language
echoesClient.getRandomQuoteByLanguage('en')
  .then(quotes => console.log('English Quotes:', quotes))
  .catch(error => console.error('Error:', error));