Codey Generator API
Generate a simple, verified example project for any combination of Arduino/ESP32 boards, sensors and modules: an Arduino sketch, a wiring diagram and a connection table.
Introduction
The Codey Generator API is a REST API for electronics webshops. You send the components of a product, or of a bundle, and Codey returns:
- An example sketch (
.ino). It is short and beginner-friendly, and it is compiled for the chosen board witharduino-clibefore you receive it. The comments are written in the language you ask for. - A wiring diagram (WebP). It is the same drawing the Codey Online IDE makes, with real product photos and pin positions.
- A connection table (WebP). It lists every wire from board pin to module pin, in the same colours as the drawing.
- The same information as JSON (
connections,wiring), so you can build your own layout.
All requests go to https://api.codey.online/v1 and use JSON over HTTPS. Generations are asynchronous and typically finish in 20–90 seconds.
Getting access
- Request access with your company details and webshop URL. This account is separate from a normal Codey user account.
- Confirm your email address. We review the request, usually within one working day.
- Once approved, log in to the dashboard and create an API key.
| Key | Prefix | What it does |
|---|---|---|
| Test key | cdy_test_ | Always returns the same example (HC-SR04 on an Arduino Uno), with real images, webhooks and the full response format. It uses no AI and no credits and does not count towards your daily limit. Build your integration with this key. |
| Live key | cdy_live_ | Real generations for your components. |
Authentication
Send the key as a bearer token with every request:
Authorization: Bearer cdy_live_4fQ9…
A missing or wrong key returns 401. An account that is not active (pending, suspended) returns 403 account_not_active.
Quick start
1. Create a generation
curl -X POST https://api.codey.online/v1/generations \ -H "Authorization: Bearer $CODEY_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: sku-10023-v1" \ -d '{ "board": "esp32-devkit-v1", "components": [ { "id": "hc-sr04" }, { "name": "0.96 inch OLED I2C SSD1306" } ], "prompt": "Show the measured distance in cm on the OLED", "language": "en", "external_reference": "SKU-10023" }'
Response 202 Accepted:
{
"id": "gen_hDl7j574YsFNMhbLTfKiOODy",
"object": "generation",
"status": "queued",
"board": { "id": "esp32-devkit-v1", "name": "ESP32 DEVKIT V1", "fqbn": "esp32:esp32:esp32doit-devkit-v1" },
"components": [
{ "input": "hc-sr04", "id": "hc-sr04", "name": "HC-SR04", "match": "id" },
{ "input": "0.96 inch OLED I2C SSD1306", "id": "oled-display-096-inch", "match": "id" }
],
…
}
2. Wait for the result. Poll GET /generations/{id} every 10 seconds (the response carries Retry-After: 10), or set a webhook.
curl https://api.codey.online/v1/generations/gen_hDl7j574YsFNMhbLTfKiOODy -H "Authorization: Bearer $CODEY_KEY"
3. Publish. Download result.images.wiring_diagram.url and result.images.connection_table.url. Show result.sketch.content in a code block, or offer GET /generations/{id}/sketch as an .ino download.
Creating a generation
POST /generations
| Field | Type | Description |
|---|---|---|
components * | array (1–8) | Each item is {"id": "…"} (a Codey catalog id, which is exact and recommended) or {"name": "…"} (a product name that is matched against the catalog). Optional quantity (1–8). |
board | string | A board id from GET /boards, for example arduino-uno or esp32-devkit-v1, or auto to let Codey choose (see Choosing the board). If you leave it out, the board is arduino-uno. If the product is a board, you may pass it in components instead. |
prompt | string (≤ 500) | Optional. What the example should do, for example "Blink the LED when motion is detected". Without it, Codey makes a typical 5-minute demo of the part. |
language | string | en (default), nl, de, fr, es, it or pl. This sets the language of the code comments, the title, the explanation and the texts in the images. |
external_reference | string (≤ 190) | Your own id, for example the SKU. It is returned as-is and you can filter on it with GET /generations?external_reference=. |
webhook_url | https URL | Where the completion event is sent. This overrides the default webhook URL of your account. |
options.image_width | integer | Width of both images in pixels, from 800 to 2400. The default is 1600. |
Header Idempotency-Key (optional, ≤ 100 characters): if you send the same key with the same body again, you get the original generation back (200, header Idempotent-Replayed: true). The same key with a different body returns 409. Use it to retry safely after a network error.
Choosing the board
You decide which board the example is for. Codey never swaps it for another board without being asked.
- If a component in
componentsis itself a board, for example an ESP32 DevKit sold as a product, that board is used. - Otherwise the
boardfield is used: an id fromGET /boards. We recommend ids over FQBNs, because several boards can share one FQBN. - If there is no
boardfield, the board is the Arduino UNO. "board": "auto"lets Codey pick, with fixed and explainable rules:Situation Board selection.reasonThe prompt or a component needs WiFi, Bluetooth, a web page, MQTT, … ESP32 DevKit V1 wirelessA component uses I2S (MEMS microphone, I2S amplifier) ESP32 DevKit V1 i2sA component only tolerates 3.3V logic (e.g. RC522, 3.3V BME280) ESP32 DevKit V1 3v3_partsMore than 18 signal pins are needed Arduino Mega 2560 many_pinsAnything else Arduino UNO default
The response always shows how the board was chosen: board.selection is {"mode": "specified" | "default" | "auto", "reason", "explanation"}.
Voltage safety. The board decides the logic voltage: UNO, Nano, Mega and UNO R4 are 5V, while ESP32 and ESP8266 are 3.3V. Codey checks every diagram before it is published. A 5V signal is never wired straight into a 3.3V pin; it gets a resistor divider or a level shifter, and I²C always gets a level shifter. A 3.3V-only part on a 5V board is powered from 3.3V and gets its inputs through a level shifter. Diagrams that fail the check are redrawn automatically.
Components & boards
Codey only draws parts it knows: it needs the real pin names and a photo of each part. Your products must therefore match the Codey catalog.
GET /boards: supported boards (id, name, FQBN).GET /components?search=oled: search the catalog.GET /components/{id}returns a single component with its pins.POST /components/resolvewith{"names": ["…", "…"]}(up to 20): matches your product names to catalog ids. It is free. Run it once over your assortment, store the ids, and send ids from then on.
POST /components/resolve
{ "names": ["HC-SR501 PIR motion sensor", "DHT22 temperature sensor"] }
→ { "data": [
{ "input": "HC-SR501 PIR motion sensor", "status": "matched", "component": { "id": "hc-sr501-pir-motion-sensor", … } },
{ "input": "DHT22 temperature sensor", "status": "ambiguous",
"suggestions": [ { "id": "dht11-module", "score": 0.62 }, … ] } ] }
Matching is careful on purpose. If a name contains a model code (DHT22, NRF24L01, …), the match must carry the same code. "DHT22" is never turned into a DHT11, because a wrong part on a product page is worse than no diagram.
POST /generations cannot be matched, the request fails with 422 unknown_component. No credits are used, and the response includes details.components[].suggestions. Missing parts are automatically queued for addition to the Codey catalog, so try again later or ask us to prioritise a part.The result
When status is succeeded, the generation contains result:
| Field | Description |
|---|---|
title, explanation | A short title and 2–4 sentences about what the circuit does, in the requested language. |
sketch.content | The full sketch. It starts with a fixed Codey.online header comment (see Attribution). |
sketch.libraries | Arduino Library Manager libraries with the exact versions it was compiled with. |
sketch.compile_verified | true: the sketch compiled for sketch.board.fqbn. |
connections[] | Every wire: {from: {part, label, pin}, to: {part, label, pin}, color}. GND wires are black, 5V wires red and 3.3V wires dark orange. |
images.wiring_diagramimages.connection_table | {url, width, height, bytes, format: "webp"}. The URLs are public and unguessable, and they are cached for a year. |
wiring | The raw Codey wiring JSON (parts + connections). |
attribution | A ready-made text and HTML snippet to place near the images. |
warnings[] | Non-fatal remarks. For example component_without_photo: that part has no photo yet and is drawn as a labelled block. |
A failed generation has status: "failed" and error: {code, message}. The code is compile_failed or generation_failed. Failed generations are never charged. Codey retries internally before it gives up, so a failure usually means the combination is not supported, for example a library that does not exist for that board.
Hosting the images. You may hotlink the asset URLs, but we recommend downloading them and serving them from your own CDN. The images are generated once and do not change.
Polling & webhooks
Set a default webhook URL in the dashboard, or send webhook_url with a generation. When a generation finishes we send a POST request:
POST https://your-shop.example/hooks/codey
Codey-Event: generation.succeeded
Codey-Signature: t=1789808019,v1=7f8c1310dd29…
{ "id": "evt_…", "object": "event", "type": "generation.succeeded", "created_at": "…", "data": { /* the full generation */ } }
Verify the signature. v1 = HMAC-SHA256 of "{t}.{raw body}" with your webhook secret, which you can find in the dashboard. Reject events whose t is more than 5 minutes old. Respond with any 2xx within 15 seconds. Failed deliveries are retried after 1 minute, 10 minutes and 1 hour. The same event can arrive more than once, so deduplicate on id.
$body = file_get_contents('php://input');
preg_match('/t=(\d+),v1=([0-9a-f]+)/', $_SERVER['HTTP_CODEY_SIGNATURE'] ?? '', $m);
$expected = hash_hmac('sha256', $m[1] . '.' . $body, getenv('CODEY_WEBHOOK_SECRET'));
if (!$m || !hash_equals($expected, $m[2]) || abs(time() - (int) $m[1]) > 300) {
http_response_code(400); exit;
}
$event = json_decode($body, true);
if ($event['type'] === 'generation.succeeded') {
$gen = $event['data']; // $gen['external_reference'], $gen['result']['images'], …
}
http_response_code(200);
import crypto from 'node:crypto'; // Express: app.post('/hooks/codey', express.raw({ type: 'application/json' }), handler) function handler(req, res) { const [, t, v1] = /t=(\d+),v1=([0-9a-f]+)/.exec(req.get('Codey-Signature') || '') || []; const expected = crypto.createHmac('sha256', process.env.CODEY_WEBHOOK_SECRET) .update(`${t}.${req.body}`).digest('hex'); if (!v1 || !crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1)) || Math.abs(Date.now() / 1000 - Number(t)) > 300) return res.sendStatus(400); const event = JSON.parse(req.body); // event.type === 'generation.succeeded' → event.data.result res.sendStatus(200); }
import hmac, hashlib, json, re, time, os
def verify(raw_body: bytes, header: str) -> dict:
m = re.match(r"t=(\d+),v1=([0-9a-f]+)", header or "")
if not m or abs(time.time() - int(m[1])) > 300:
raise ValueError("bad signature")
expected = hmac.new(os.environ["CODEY_WEBHOOK_SECRET"].encode(),
m[1].encode() + b"." + raw_body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, m[2]):
raise ValueError("bad signature")
return json.loads(raw_body)
Processing a whole catalog
- Map your products once with
POST /components/resolve(20 names per call) and store the ids you accept. Products that are boards map toGET /boardsids. - Queue generations at a steady pace. At most 3 generations per account can be in progress at the same time. A 4th returns
429 too_many_in_progress, so wait for a webhook before you submit the next one. - Use
external_reference(your SKU) and anIdempotency-Keysuch as"{sku}-v1"so that retries never create duplicates. - When a webhook arrives, download the two images and attach them, together with the sketch, to the product.
Generations are meant to be made once per product. Store the results. Do not generate on every page view.
AI assistants (MCP)
Let the AI chat or shopping assistant in your webshop consult Codey directly. When a customer asks how to connect a product, or wants example code, the assistant calls Codey and gets verified facts back: pins, libraries, a compile-checked sketch and a wiring diagram image. The assistant then writes the answer in the customer's language.
This works through the Model Context Protocol. The MCP server uses your normal API key, limits and request log:
POST https://api.codey.online/v1/mcp Authorization: Bearer cdy_live_… Content-Type: application/json
Transport: Streamable HTTP, stateless. Every request is one JSON-RPC 2.0 message and every answer is application/json. There are no sessions and no server-sent events. Supported methods: initialize, ping, tools/list and tools/call. Notifications get 202. Protocol versions: 2025-06-18, 2025-03-26 and 2024-11-05.
| Tool | What it returns | Speed |
|---|---|---|
codey_product_guide | The guide you already generated for a product, looked up by its SKU (external_reference): explanation, sketch, libraries, connections and image URLs. There is one variant per board. Arguments: sku, optional board, include_code. | instant |
codey_component_info | Facts about one component: description (translated), pins, protocols, I²C address, libraries, wiring notes and, when available, a short standard example. Arguments: id or name, language. | instant |
codey_find_components | Matches product names to catalog ids, with suggestions for names it does not know. Argument: names. | ~1 s |
codey_generate_example | A new example for any combination of components (the same pipeline as POST /generations). It gets priority in the queue and waits up to wait_seconds (default 40, max 55). If the example is not ready yet, it returns status: "processing" and a generation_id. Identical requests are answered instantly from earlier results. Arguments: components, board (default auto), prompt, language, wait_seconds. | 30–90 s |
codey_get_generation | Status and result of a generation. Arguments: generation_id, optional wait_seconds. | instant |
codey_list_boards | The supported boards. | instant |
Every tool result has a short text part for the model, with the explanation, connections, code and a ready-made markdown image line for the wiring diagram. It also has a structuredContent part with the same JSON objects as the REST API. Tool errors come back as isError: true with a readable message, so the assistant can recover (for example by picking one of the suggestions). Examples made through MCP count towards your normal limits, with an extra cap of 100 per day by default, and they never trigger your webhook.
Connecting your assistant
// OpenAI Responses API: OpenAI calls the Codey MCP server itself.
POST https://api.openai.com/v1/responses
{
"model": "gpt-5.4-mini",
"instructions": "You are the shop assistant. The customer is viewing SKU OT2071-D125. …",
"input": "How do I connect this to my ESP32?",
"tools": [{
"type": "mcp",
"server_label": "codey",
"server_url": "https://api.codey.online/v1/mcp",
"headers": { "Authorization": "Bearer cdy_live_…" },
"require_approval": "never"
}]
}
// Anthropic Messages API with the MCP connector (see Anthropic's docs for the current beta header).
POST https://api.anthropic.com/v1/messages
anthropic-beta: mcp-client-2025-04-04
{
"model": "…",
"max_tokens": 2000,
"messages": [{ "role": "user", "content": "How do I connect this to my ESP32?" }],
"mcp_servers": [{
"type": "url",
"url": "https://api.codey.online/v1/mcp",
"name": "codey",
"authorization_token": "cdy_live_…"
}]
}
# 1. Fetch the tool definitions once (cache them) and turn each into a
# function definition for your model: name, description, inputSchema → parameters.
curl https://api.codey.online/v1/mcp -H "Authorization: Bearer $CODEY_KEY" -H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
# 2. When the model calls a tool, forward it and give result.content[0].text back to the model.
curl https://api.codey.online/v1/mcp -H "Authorization: Bearer $CODEY_KEY" -H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call",
"params":{"name":"codey_product_guide","arguments":{"sku":"OT2071-D125"}}}'
Tips for the assistant prompt: put the SKU of the product the customer is viewing in the prompt, so the assistant can call codey_product_guide straight away. Ask it to answer in the customer's language, to show the wiring diagram image, and to keep code short. Make sure your chat renders markdown images: the image URLs are public and can be shown directly.
Errors
Errors always have this shape, with an HTTP status code that fits:
{ "error": { "type": "invalid_request_error", "code": "unknown_component", "message": "…", "details": { … }, "request_id": "req_…" } }
| Status | code | Meaning |
|---|---|---|
| 400 | invalid_request, invalid_json | A field is missing or invalid. See details.field. |
| 401 | missing_api_key, invalid_api_key | There is no key, or the key is wrong or revoked. |
| 402 | insufficient_credits | Your credit balance is too low (only once billing is enabled). |
| 403 | account_not_active | The account is pending approval or suspended. |
| 404 | not_found | Unknown route or id. |
| 409 | idempotency_conflict | This Idempotency-Key was already used with a different body. |
| 413 | request_too_large | The body is larger than 64 KB. |
| 422 | unknown_component | One or more components are not in the catalog. See details.components[].suggestions. |
| 422 | unsupported_board, multiple_boards | The board is not supported, or more than one board was given. |
| 429 | rate_limited, too_many_in_progress, daily_limit_reached | Slow down. Check the Retry-After header. |
| 5xx | internal_error, maintenance, api_disabled | Our side. Retry with backoff and quote the request_id when you contact support. |
Limits
| Limit | Default |
|---|---|
| Requests per minute (all endpoints) | 30 |
| Generations in progress at the same time | 3 |
| Live generations per day | 100 |
| Components per generation | 8 |
Every authenticated response includes X-RateLimit-Limit and X-RateLimit-Remaining. Need more? Contact us. Limits are set per account.
Credits & pricing
During the beta, generations are free for approved accounts. Later the API will work with prepaid credits, which you top up in the dashboard and pay via Stripe. Each successful live generation will then cost a fixed number of credits. Until then:
GET /accountreturnscredits_balance,billing_enabledandprice_per_generation. We will announce any change well in advance.- Rejected requests (4xx), failed generations and test-key generations are never charged.
credits_chargedon every generation shows what it cost.
Attribution & licence
- Images: every image has a footer "© Generated by Codey.online · www.codey.online" and a subtle watermark. You may publish the images on your product pages and in your documentation, but you may not crop, remove or hide the footer or the watermark.
- Code: every sketch starts with a short header comment that refers to Codey.online. The code itself is free to use, modify and share. Please keep the header when you publish the sketch.
- Page: we recommend showing
result.attribution.htmlnear the images. It is a small line that links to Codey.online.
Full terms: API terms.
Code examples
<?php
function codey(string $method, string $path, ?array $body = null): array {
$ch = curl_init('https://api.codey.online/v1' . $path);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('CODEY_KEY'), 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => $body ? json_encode($body) : null,
]);
$res = json_decode(curl_exec($ch), true);
curl_close($ch);
return $res;
}
$gen = codey('POST', '/generations', [
'board' => 'arduino-uno',
'components' => [['id' => 'hc-sr04']],
'language' => 'nl',
'external_reference' => 'SKU-10023',
]);
do { sleep(10); $gen = codey('GET', '/generations/' . $gen['id']); }
while (in_array($gen['status'], ['queued', 'processing'], true));
if ($gen['status'] === 'succeeded') {
file_put_contents('wiring.webp', file_get_contents($gen['result']['images']['wiring_diagram']['url']));
file_put_contents('table.webp', file_get_contents($gen['result']['images']['connection_table']['url']));
file_put_contents('example.ino', $gen['result']['sketch']['content']);
}
const BASE = 'https://api.codey.online/v1';
const headers = { Authorization: `Bearer ${process.env.CODEY_KEY}`, 'Content-Type': 'application/json' };
let gen = await (await fetch(`${BASE}/generations`, {
method: 'POST', headers,
body: JSON.stringify({ board: 'esp32-devkit-v1', components: [{ id: 'hc-sr04' }], language: 'en' }),
})).json();
while (gen.status === 'queued' || gen.status === 'processing') {
await new Promise(r => setTimeout(r, 10_000));
gen = await (await fetch(`${BASE}/generations/${gen.id}`, { headers })).json();
}
console.log(gen.status, gen.result?.images.wiring_diagram.url);
import os, time, requests
BASE = "https://api.codey.online/v1"
H = {"Authorization": f"Bearer {os.environ['CODEY_KEY']}"}
gen = requests.post(f"{BASE}/generations", headers=H, json={
"board": "arduino-nano",
"components": [{"name": "5V relay module"}, {"id": "drukknop"}],
"language": "de",
}).json()
while gen["status"] in ("queued", "processing"):
time.sleep(10)
gen = requests.get(f"{BASE}/generations/{gen['id']}", headers=H).json()
print(gen["status"], gen.get("result", {}).get("title"))
The full, machine-readable specification (OpenAPI 3.1) is at https://api.codey.online/v1/openapi.json. You can also browse it in the API reference.
Versioning
The version is part of the URL (/v1). Within v1 we only make additive changes, such as new fields, new endpoints or new error codes, so ignore fields you do not know. Breaking changes will come as /v2, and v1 stays available for at least 12 months after that.
| Date | Change |
|---|---|
| 2026-09 | v1 beta: generations, catalog, resolve, webhooks, test keys. |
| 2026-10 | MCP server at /v1/mcp for AI assistants. |