Guide 2.1: Developer Guide

Using SdashAPI with JavaScript

JavaScript is the fundamental language of the web. In this guide, we will explore how to interact with the SdashAPI directly from your frontend applications using modern Vanilla JavaScript, asynchronous functions, and the native Fetch API.

The Fetch API

2.1.1

The native fetch() API provides a modern, powerful, and flexible feature set for making network requests. It is built into all modern web browsers, meaning you do not need to install any external libraries (like Axios or jQuery) to communicate with SdashAPI.

Because network requests take time to complete, fetch() returns a Promise. We highly recommend using the modern async/await syntax to handle these Promises, as it makes your code much cleaner, easier to read, and simpler to debug compared to older callback methods.

Writing the Request Function

2.1.2

To make our request, we need to pass two arguments to the fetch() function: the URL of the SdashAPI endpoint (including our query parameters), and a configuration object that contains our custom AccessToken header.

Here is a complete, production-ready function that fetches a WAEC Economics question:

async function getPastQuestion() {
  const apiUrl = 'https://sdashapi.com/api/v1/q?type=wassce&subject=economics';
  const apiKey = 'YOUR_API_KEY_HERE';

  try {
    // Await the network response
    const response = await fetch(apiUrl, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'AccessToken': apiKey
      }
    });

    // Parse the JSON data
    const data = await response.json();

    // Check if the API returned a successful status
    if (data.status === 200) {
      console.log('Question:', data.data.question);
      console.log('Options:', data.data.option);
      console.log('Correct Answer:', data.data.answer);
    } else {
      console.error('API Error:', data.message);
    }

  } catch (error) {
    // This catches network errors (e.g. no internet connection)
    console.error('Network Error:', error);
  }
}

// Execute the function
getPastQuestion();

Security Considerations

2.1.3

While it is incredibly easy to call SdashAPI directly from your frontend JavaScript code, you must be extremely cautious. If you embed your raw API key in a client-side JavaScript file, anyone can open their browser's developer tools and copy it.

For simple projects or hackathons, client-side requests are perfectly fine. However, for a production application, you should always route your requests through your own backend server (which securely stores your API key), and have your frontend JavaScript communicate with your backend instead.

Building a backend?

Next, we will look at how to implement the exact same request using Python.

Next Guide: Using Python →
Avatar

How can we help?

We reply immediately

Hello! 👋 How can we help you today?