Build a Painting of the Day Widget with the Art Search API
This tutorial builds a small "painting of the day" widget: every visitor sees the same painting all day, a button shows its dates and description, and a second button pulls a random artwork from the Random Artwork API. A Node.js proxy of about 140 lines keeps your API key off the page and your request count low.
What you need
- A free Art Search API key from the console. The free plan includes 50 requests a day for non-commercial sites with a link back to Art Search; the widget includes that link.
- Node.js 18 or newer, which has
fetchbuilt in. No npm packages are needed. - Two files in one folder:
server.jsandindex.html.
How it works
The browser talks only to your server, and your server talks to Art Search. The API allows browser requests from any origin, but a key in your page's JavaScript is visible to every visitor, who could then spend your quota. The proxy has three routes:
| Your route | Art Search call | Returns |
|---|---|---|
/api/painting-of-the-day | GET /artworks?query=THEME&type=painting&number=1&offset=N | id, title and image of today's painting |
/api/artworks/{id} | GET /artworks/{id} | title, image, start and end date, description |
/api/random-artwork | GET /artworks/random | the same fields for a random artwork |
Picking the day's painting. The Search Artworks endpoint with type=painting and number=1 returns one painting, and offset chooses its position in the results. The server uses the day of the year (0 to 365) as the offset, so every visitor and every refresh on the same day asks for the same position, and the painting changes at midnight UTC. An optional theme (for example "still life with flowers") becomes the search query. If a theme has fewer matches than the offset, the server wraps around with offset % available.
Details on demand. Search results contain only id, title and image. The dates and description come from the Retrieve Artwork endpoint, which the widget calls only when someone clicks "About this painting".
Random artworks. The Random Artwork endpoint returns one random artwork of any type, from paintings to sculptures and swords, with all its details in a single request.
Caching and the Art Search terms
The Art Search terms don't allow storing API data. With prior written permission, you may cache data your users requested for up to one hour. The server follows that rule:
- Responses are kept in memory for at most one hour (
CACHE_SECONDS, capped at 3600) and deleted within a minute after they expire. Nothing is written to disk. - Ask for permission at mail@artsearch.io before you deploy with the cache on, or start the server with
CACHE_SECONDS=0to turn it off. - The painting stays the same all day because of the date-based offset, not because the server stores it.
Step 1: Set your API key
Keep the key in an environment variable, never in the HTML:
export ARTSEARCH_API_KEY=your-key Step 2: Write the proxy server
Save this as server.js:
// server.js: a small proxy for the painting of the day widget. No dependencies.
// Run with Node.js 18 or newer: ARTSEARCH_API_KEY=your-key node server.js
const http = require('node:http');
const fs = require('node:fs/promises');
const path = require('node:path');
const API_URL = 'https://api.artsearch.io';
const API_KEY = process.env.ARTSEARCH_API_KEY;
const PORT = Number(process.env.PORT) || 3000;
const THEME = process.env.THEME || ''; // optional search query, e.g. "still life with flowers"
// Art Search's terms allow caching only with prior written permission, and for one hour at most.
const CACHE_MS = Math.min(Number(process.env.CACHE_SECONDS ?? 3600), 3600) * 1000;
const RANDOM_PER_DAY = Number(process.env.RANDOM_PER_DAY ?? 10); // budget for "Show a random artwork"
if (!API_KEY) {
console.error('Set the ARTSEARCH_API_KEY environment variable.');
process.exit(1);
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function httpError(status, message) {
return Object.assign(new Error(message), { status });
}
// Calls to Art Search go out one at a time, at most one per second (the Free plan's limits).
let queue = Promise.resolve();
let lastCall = 0;
function artSearch(pathAndQuery) {
const task = queue.then(async () => {
for (let attempt = 1; ; attempt++) {
const wait = lastCall + 1000 - Date.now();
if (wait > 0) await sleep(wait);
lastCall = Date.now();
const response = await fetch(API_URL + pathAndQuery, { headers: { 'x-api-key': API_KEY } });
if (response.status === 429 && attempt < 3) {
const retryAfter = Number(response.headers.get('retry-after'));
await sleep(retryAfter > 0 ? retryAfter * 1000 : 1000 * 2 ** attempt);
continue;
}
if (response.status === 402) throw httpError(402, 'The daily quota is used up. It resets at midnight UTC.');
if (response.status === 429) throw httpError(429, 'Too many requests. Try again in a minute.');
if (!response.ok) throw httpError(502, `Art Search answered with HTTP ${response.status}.`);
console.log(`${pathAndQuery}: ${response.headers.get('x-api-quota-left')} requests left today`);
return response.json();
}
});
queue = task.catch(() => {}); // keep the queue going after an error
return task;
}
// In-memory cache: entries expire after CACHE_MS and are deleted, nothing is written to disk.
const cache = new Map();
function deleteExpired() {
const now = Date.now();
for (const [k, entry] of cache) if (entry.expires <= now) cache.delete(k);
}
setInterval(deleteExpired, 60 * 1000).unref(); // also on a quiet site, within a minute of expiry
function cached(key, load) {
const now = Date.now();
deleteExpired();
if (cache.has(key)) return cache.get(key).value;
const value = load();
if (CACHE_MS > 0) {
cache.set(key, { expires: now + CACHE_MS, value });
value.catch(() => cache.delete(key)); // never cache an error
}
return value;
}
const todayUTC = () => new Date().toISOString().slice(0, 10); // e.g. "2026-11-22"
function dayOfYear(isoDate) {
const date = new Date(isoDate + 'T00:00:00Z');
return Math.round((date - Date.UTC(date.getUTCFullYear(), 0, 1)) / 86400000); // 0 to 365
}
// Ids the widget has shown today. The details route only answers for these, so nobody can
// spend your quota by asking for thousands of other ids.
let shown = { date: '', ids: new Set() };
function remember(artwork) {
const date = todayUTC();
if (shown.date !== date) shown = { date, ids: new Set() };
shown.ids.add(String(artwork.id));
return artwork;
}
// The day's painting is result number N of a fixed search, where N is the day of the year.
// Every visitor and every cache refresh on the same day asks for the same position.
async function paintingOfTheDay() {
const date = todayUTC();
return remember(await cached('day:' + date, async () => {
// Always send a query: an empty one when no theme is set.
const params = new URLSearchParams({ query: THEME, type: 'painting', number: '1', offset: String(dayOfYear(date)) });
let page = await artSearch('/artworks?' + params);
if (page.artworks.length === 0 && page.available > 0) {
// Fewer matches than days in the year: wrap around.
params.set('offset', String(dayOfYear(date) % page.available));
page = await artSearch('/artworks?' + params);
}
const artwork = page.artworks[0];
if (!artwork) throw httpError(404, 'No painting matches this theme.');
return { date, id: artwork.id, title: artwork.title, image: artwork.image };
}));
}
const details = (a) => ({
id: a.id, title: a.title, image: a.image,
start_date: a.start_date, end_date: a.end_date, description: a.description,
});
function artworkDetails(id) {
return cached('artwork:' + id, async () => details(await artSearch('/artworks/' + id)));
}
let randomBudget = { date: '', left: 0 };
async function randomArtwork() {
const date = todayUTC();
if (randomBudget.date !== date) randomBudget = { date, left: RANDOM_PER_DAY };
if (randomBudget.left <= 0) throw httpError(429, 'No more random artworks today. Come back tomorrow.');
randomBudget.left--;
return remember(details(await artSearch('/artworks/random'))); // a new artwork on every click, not cached
}
function sendJson(res, status, body) {
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
res.end(JSON.stringify(body));
}
http.createServer(async (req, res) => {
try {
const { pathname } = new URL(req.url, 'http://localhost'); // throws on a malformed URL: answered with 500 below
if (pathname === '/api/painting-of-the-day') return sendJson(res, 200, await paintingOfTheDay());
if (pathname === '/api/random-artwork') return sendJson(res, 200, await randomArtwork());
const match = pathname.match(/^\/api\/artworks\/(\d{1,8})$/);
if (match && !shown.ids.has(match[1])) return sendJson(res, 404, { error: 'Unknown artwork' });
if (match) return sendJson(res, 200, await artworkDetails(match[1]));
if (pathname === '/') {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
return res.end(await fs.readFile(path.join(__dirname, 'index.html')));
}
sendJson(res, 404, { error: 'Not found' });
} catch (error) {
// 402 (quota used up) and 429 (too many requests) are temporary, so answer 503.
const status = [402, 429].includes(error.status) ? 503 : error.status || 500;
sendJson(res, status, { error: error.message });
}
}).listen(PORT, () => console.log(`Widget running at http://localhost:${PORT}/`)); What the important parts do:
artSearch()sends requests one at a time and at least one second apart, which stays within the free plan's limits of 60 requests per minute and 1 concurrent request (rate limits). The key goes in thex-api-keyheader.- HTTP 429 (rate limit) is retried twice, after the
Retry-Afterheader if the response has one, otherwise after 2 and 4 seconds. - HTTP 402 means the free plan's daily quota is used up; it resets at midnight UTC. The server answers 503 with a readable message instead of passing the error through.
cached()stores the promise, not just the result, so several visitors arriving at the same moment share one API call. Failed calls are never cached.RANDOM_PER_DAYcaps the random button (10 clicks a day by default), and/api/artworks/{id}only answers for artworks the widget has shown that day, so visitors can't use up your quota through the proxy.
Step 3: Write the widget
Save this as index.html next to server.js. The server serves it at /:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Painting of the day</title>
<style>
.potd { max-width: 420px; margin: 0; font-family: Georgia, serif; }
.potd img { display: block; width: 100%; height: 320px; object-fit: contain; background: #f4f1ea; }
.potd figcaption { padding: 12px 0; line-height: 1.4; }
.potd-title { display: block; font-size: 1.15rem; }
.potd-dates, .potd small { color: #666; }
.potd button { margin: 8px 8px 0 0; }
</style>
</head>
<body>
<figure class="potd">
<img id="potd-image" alt="" decoding="async" hidden>
<figcaption>
<strong id="potd-title" class="potd-title">Loading today's painting…</strong>
<span id="potd-dates" class="potd-dates"></span>
<p id="potd-description" hidden></p>
<button id="potd-more" type="button" hidden>About this painting</button>
<button id="potd-random" type="button">Show a random artwork</button>
<br><small>Artwork data from <a href="https://artsearch.io/">Art Search</a></small>
</figcaption>
</figure>
<script>
const $ = (id) => document.getElementById(id);
function years(art) {
const year = (y) => (y < 0 ? -y + ' BCE' : String(y));
if (art.start_date == null) return '';
if (art.end_date == null || art.end_date === art.start_date) return year(art.start_date);
return year(art.start_date) + '–' + year(art.end_date);
}
async function getJson(url) {
const response = await fetch(url);
const body = await response.json();
if (!response.ok) throw new Error(body.error || 'Request failed');
return body;
}
function show(art) {
$('potd-image').src = art.image;
$('potd-image').alt = art.title;
$('potd-image').hidden = false;
$('potd-title').textContent = art.title;
$('potd-dates').textContent = years(art);
const firstParagraph = (art.description || '').split('\n')[0].trim();
$('potd-description').textContent = firstParagraph;
$('potd-description').hidden = !firstParagraph;
$('potd-more').hidden = Boolean(firstParagraph);
$('potd-more').onclick = () => load('/api/artworks/' + art.id);
}
async function load(url) {
try {
show(await getJson(url));
} catch (error) {
$('potd-title').textContent = error.message;
}
}
$('potd-random').onclick = () => load('/api/random-artwork');
load('/api/painting-of-the-day');
</script>
</body>
</html> Notes on the front end:
- Text is set with
textContent, so a title can never inject HTML into your page. - The
imageURL points to the full-size file, which can be several megabytes. The CSS gives the image a fixed height withobject-fit: containso the layout doesn't jump while it loads. - The description comes as paragraphs separated by line breaks; the widget shows the first one.
- The "Artwork data from Art Search" link is the backlink the free plan requires.
Step 4: Run it
ARTSEARCH_API_KEY=your-key node server.js
# Widget running at http://localhost:3000/ Open http://localhost:3000/. The server logs every Art Search call with the number of requests left today, read from the X-API-Quota-Left response header. You can also call the routes directly:
curl http://localhost:3000/api/painting-of-the-day
curl http://localhost:3000/api/random-artwork Optional settings, all as environment variables: PORT, THEME (a search query such as "winter landscape"), CACHE_SECONDS (0 to 3600) and RANDOM_PER_DAY.
How many requests the widget uses
| Feature | Art Search requests | Most per day |
|---|---|---|
| Painting of the day | 1 per cache period (2 if the theme needs a wrap-around) | 24 with a one-hour cache |
| About this painting | 1 per artwork per cache period | 24 for the day's painting |
| Show a random artwork | 1 per click | RANDOM_PER_DAY (default 10) |
The maximums assume visitors every hour of the day. On a personal site the free plan's 50 requests a day are usually enough; if the widget is busy around the clock, lower RANDOM_PER_DAY or move to the Apprentice plan with 500 requests a day and commercial use (pricing). Without the cache, every page view costs a request.
Variations
- Only landscape-format images: add
params.set('min-ratio', '1.2')inpaintingOfTheDay(); the ratio is width divided by height. - One period: add
earliest-start-dateandlatest-start-date, for example 1850 and 1900. - Other artwork types: replace
type=paintingwithdrawing,print,photographor another value from the list of types. - Serverless hosting: the three routes are plain functions, so they port to a serverless platform. The in-memory cache then lives per instance; keep the one-hour limit.
For more on queries and filters, read semantic art search in Python. To see random artworks without writing code, try the random artwork generator.