Save to file

This code snippet demonstrates how to save the response from the APIs to a file in JSON format. It includes examples for both JSON and CSV formats.

Ensure you have the necessary permissions to write files in the directory where this script is executed.

Below is the code snippet that you can use to save the API response to a file:


const axios = require("axios");
const fs = require("fs"); 
const { Parser } = require("json2csv"); 

const BASE_URL = "https://www.example.co.za/api";
const AUTH_URL = `${BASE_URL}/Auth/GetToken`;
//CitizenData, RefugeeData, and LineageData
const API_URL = `${BASE_URL}/{endpoint}`; // Replace {endpoint} with the specific endpoint you want to access

const authData = {
  tenantKey: "your_tenant_key",
  tenantSecret: "your_tenant_secret",
  expiresAt: "2025-12-20T16:03:20.656Z"
};

const requestData = {
  identityNumber: "your_identity_number"
  // Uncomment if verifying for refugee
  // "fileNumber": "",
  // "citizenIDNumber": ""
};

async function fetchData() {
  try {
    // Get token
    const authResponse = await axios.post(AUTH_URL, authData, {
      headers: { "Content-Type": "application/json" }
    });

    const token = authResponse.data.token || authResponse.data.accessToken;
    console.log("Authenticated successfully.");

    // Fetch data
    const response = await axios.post(API_URL, requestData, {
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json"
      }
    });

    const data = response.data;
   
    // --- Save as JSOn ---
    fs.writeFileSync("verified_data.json", JSON.stringify(data, null, 2));
    console.log("Data saved to output.json");

    // --- Save as CSV ---
    try {
      const parser = new Parser();
      const csv = parser.parse(Array.isArray(data) ? data : [data]); 
      fs.writeFileSync("verified_data.csv", csv);
      console.log("Data saved to output.csv");
    } catch (csvErr) {
      console.error("CSV conversion error:", csvErr.message);
    }

  } catch (error) {
    if (error.response) {
      console.error("Error data:", error.response.data);
      console.error("Error status:", error.response.status);
      console.error("Error statusText:", error.response.statusText);
    } else {
      console.error("Error:", error.message);
    }
  }
}

fetchData();



$baseUrl = "https://www.example.co.za/api";

$authUrl = "$baseUrl/Auth/GetToken";
$apiUrl  = "$baseUrl/CitizenData";

$authContext = stream_context_create([
    "http" => [
        "header" => "Content-Type: application/json\r\n",
        "method" => "POST",
        "content" => json_encode([
            "tenantKey" => "your_tenant_key",
            "tenantSecret" => "your_tenant_secret",    
            "expiresAt"    => "2025-12-20T16:03:20.656Z"
        ]),
        "ignore_errors" => true
    ]
]);

$authResponse = file_get_contents($authUrl, false, $authContext);

if ($authResponse === false) {
    die("Error fetching auth token.");
}

$authResult = json_decode($authResponse, true);
$token = $authResult["token"] ?? $authResult["accessToken"] ?? null;

if (!$token) {
    die("Authentication failed. No token received.");
}

echo "Authenticated successfully.\n";

$apiContext = stream_context_create([
    "http" => [
        "header" => "Authorization: Bearer $token\r\n" .
                    "Content-Type: application/json\r\n",
        "method" => "POST",
        "content" => json_encode([
            "identityNumber" => "your_identity_number"
        ]),
        "ignore_errors" => true
    ]
]);

$response = file_get_contents($apiUrl, false, $apiContext);

if ($response === false) {
    die("Error making request.");
}

$data = json_decode($response, true);

// uncomment if you to save data in JSON format
// file_put_contents("citizenData.json", json_encode($data, JSON_PRETTY_PRINT));
// echo "Saved data to citizenData.json\n";

if (is_array($data)) {
    $fp = fopen("citizenData.csv", "w");
    if (array_keys($data) !== range(0, count($data) - 1)) {
        $data = [$data];
    }
    fputcsv($fp, array_keys($data[0]));
    foreach ($data as $row) {
        fputcsv($fp, $row);
    }

    fclose($fp);
    echo "Saved data to citizenData.csv\n";
} else {
    echo "Response is not valid JSON, cannot save to CSV.\n";
}