Guide 2.3: Developer Guide

Using SdashAPI with PHP

PHP remains one of the most robust and widely used languages for server-side web development. Making server-to-server HTTP requests in PHP ensures that your API key remains hidden from the client browser. In this guide, we will use PHP's cURL extension to fetch data from SdashAPI.

Configuring the cURL Request

2.3.1

The cURL library in PHP is incredibly powerful but requires a few lines of configuration to properly set the URL, inject our custom AccessToken header, and ensure the response is returned as a string rather than echoed directly to the output buffer.

Here is the standard pattern for fetching a NECO Chemistry question:

<?php

// Define the API URL with query parameters
$url = "https://sdashapi.com/api/v1/q?type=neco&subject=chemistry";

// Initialize the cURL session
$ch = curl_init($url);

// Configure cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPGET, true);

// Set the required headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: application/json",
    "AccessToken: YOUR_API_KEY_HERE"
]);

// Execute the request
$response = curl_exec($ch);

// Check for cURL errors
if(curl_errno($ch)){
    echo 'Request Error: ' . curl_error($ch);
} else {
    // Decode the JSON response into a PHP associative array
    $data = json_decode($response, true);
    
    // Validate the API status
    if (isset($data['status']) && $data['status'] === 200) {
        $question = $data['data']['question'];
        $answer = strtoupper($data['data']['answer']);
        $solution = $data['data']['solution'];
        
        echo "<h3>Question:</h3> <p>{$question}</p>";
        echo "<strong>Answer:</strong> {$answer} <br>";
        echo "<strong>Solution:</strong> {$solution}";
    } else {
        echo "Failed to retrieve data from the API.";
    }
}

// Close the cURL session
curl_close($ch);
?>

Building with modern JavaScript?

Next, we will look at how to run server-side JavaScript using Node.js.

Next Guide: Using Node.js →
Avatar

How can we help?

We reply immediately

Hello! 👋 How can we help you today?