Skip to content
Tutorials Center
My learning

Topics

Lesson 137 of 147 Β· Projects

Project: Public API Dashboard

Build a statistics dashboard from a public JSON API in PHP - fetch with cURL, handle errors, cache responses with a TTL, aggregate the data and render an HTML table and an SVG bar chart.

Public data APIs publish everything from weather and exchange rates to disease statistics and space launches. A dashboard takes such an API and turns it into something a person can read: a table of the latest numbers, a chart of the trend, perhaps a "top 5" list. It is a perfect PHP project because it combines the skills of the earlier sections in one realistic job: calling an HTTP API, decoding JSON, coping with failures, caching so you do not hammer someone else's server, and building HTML.

We will make a dashboard for a "daily cases per country" style API (the structure used by COVID-style trackers, but the same code works for any list of records). The editor has no outgoing network access, so the program talks to a stand-in API function that returns exactly the JSON a real service would. Swapping in the real curl call (shown in stage 1) changes one line.

You need JSON, REST APIs, Caching Strategies, File Handling and Errors and Exceptions.

The plan

flowchart LR
  A["Visitor opens dashboard"] --> B{"Cache fresh?"}
  B -->|"yes"| E["Use cached JSON"]
  B -->|"no"| C["cURL the API"]
  C -->|"ok"| D["Save to cache"]
  C -->|"error"| F["Use stale cache if any"]
  D --> E
  F --> E
  E --> G["Aggregate: totals, top 5, trend"]
  G --> H["HTML table + SVG chart"]

The API is called at most once per cache lifetime, and an outage shows old data instead of an error page.

Stage 1: fetching and decoding

A robust fetch function does five things: sets a timeout, follows no more than a few redirects, checks the HTTP status, decodes JSON with JSON_THROW_ON_ERROR and turns every failure into one exception type that the rest of the program understands. The real cURL version is read-only here:

PHP
function fetchJson(string $url): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 3,
        CURLOPT_HTTPHEADER     => ['Accept: application/json'],
        CURLOPT_USERAGENT      => 'MyDashboard/1.0',
    ]);
    $body = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $error = curl_error($ch);

    if ($body === false) {
        throw new ApiException("Network error: $error");
    }
    if ($status !== 200) {
        throw new ApiException("API answered HTTP $status");
    }
    try {
        return json_decode($body, true, 32, JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        throw new ApiException('The API returned invalid JSON', 0, $e);
    }
}

In the runnable version below, a fakeApi() function plays the part of the network, including a failure mode so you can test the error handling.

PHP Stage 1: a fetcher with one exception type

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real APIs also answer 429 Too Many Requests when you call too often and 401 when a key is wrong, which is why the next stage exists. Keep API keys in environment variables, never in the code (see Deployment).

Stage 2: a file cache with a time to live

Calling an API on every page view is slow and rude, and many APIs enforce limits. A cache stores the last good response with a timestamp. The rules we want:

  1. If the cached copy is younger than the TTL (say 10 minutes), use it.
  2. Otherwise try the API; on success save the new copy.
  3. If the API fails and any cached copy exists, use it anyway ("stale-if-error") and mark it as stale.

Write the cache file atomically (write to a temporary name, then rename()) so a visitor never reads a half-written file.

PHP Stage 2: caching with stale-if-error

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

On a busy site many requests may find the cache expired at the same moment and all call the API (a "cache stampede"). Protect against it with flock() around the refresh, or refresh from a cron job instead (see Caching Strategies). For shared hosting, files are fine; with several servers use Redis.

Stage 3: aggregate and render a table

Raw records become useful when you compute things from them: the total per country, the change since the previous day, the 7-day average, a top 5. This is array work: array_map, array_sum, usort and array_slice do nearly all of it (see Functional Array Functions). Rendering is a plain HTML table, with every value escaped because it came from outside.

PHP Stage 3: statistics and an HTML table

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The country named CΓ΄te d'Ivoire <test> shows that e() neutralizes markup in data (see XSS and Output Escaping). Locale-aware formatting of numbers and dates is covered in Internationalization.

Stage 4: a chart with inline SVG

You do not need a JavaScript library for a simple chart. SVG is just XML, so PHP can print it, and it scales perfectly and is accessible when you add a <title>. Below, a function turns the 7 daily values of one country into a bar chart: scale each value to the height, then draw a <rect> per bar and a <text> label.

PHP Stage 4: SVG bar chart

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Paste the printed SVG into an .svg file or straight into an HTML page and the chart appears. Notice that every number printed into the markup is either computed by you or passed through sprintf('%d'), and the text titles are escaped.

Putting it together

On a real server the finished dashboard is a single file, index.php, that combines the stages:

PHP
<?php
$cache = new FileCache(__DIR__ . '/cache', ttl: 600);

try {
    $result = load($cache, 'cases', fn() => fetchJson('https://api.example.com/v1/cases'));
    $rows = summarize($result['data']['data']);
    $notice = $result['source'] === 'api' || $result['source'] === 'cache' ? '' : 'Showing older data.';
} catch (ApiException $e) {
    http_response_code(503);
    exit('The data service is unavailable. Please try again later.');
}
?>
<h1>Cases dashboard</h1>
<p><?= e($notice) ?></p>
<?= renderTable(array_slice($rows, 0, 5)) ?>
<?= barChart($result['data']['data'][0]['cases'], 'First country, last 7 days') ?>

Never show raw exception messages to visitors (they may reveal URLs or keys); log them instead as taught in Logging with PSR-3.

Ideas for extending the project

  • Add a ?country=Japan filter, validated against a whitelist of names.
  • Add a line chart (<polyline>) for the trend, or a sparkline in each table row.
  • Let users download the table as CSV (CSV Files).
  • Refresh the cache from a cron job (Command-Line PHP) so that visitors never wait for the API.
  • Load the numbers after the page appears with AJAX.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. Why does the dashboard cache API responses?

    One cached response can serve many visitors, so your page is fast, the provider is not hammered and you still have data when it is down.
  2. 2. What does "stale-if-error" mean?

    An outage of the API should not turn into an outage of your dashboard when you still hold older data.
  3. 3. Why is the cache file written to a temporary name and then renamed?

    Between fopen and the last byte written, another request could read a truncated file. A rename swaps in the complete file in one step.
  4. 4. Why must every value from the API pass through htmlspecialchars() before being printed in the table?

    Data from outside is untrusted. Escaping turns it into harmless text.
  5. 5. What is the purpose of CURLOPT_TIMEOUT?

    Without timeouts a slow remote service can tie up all your PHP workers.

Summary

  • Wrap fetching, status checking and JSON decoding in one function that throws one exception type, and always set connection and total timeouts.
  • Cache responses with a TTL; write atomically, and fall back to stale data when the API fails.
  • Aggregate with array functions (array_map, array_sum, usort, array_slice) and format with number_format().
  • Escape every external value in HTML; SVG charts can be generated as plain strings.
  • Keep keys in the environment, log errors privately and show visitors a friendly message.

Next: Project: Upload Manager