Car logos and brand data in Python

A standard-library client for back ends, data pipelines and server-rendered templates. It returns plain dicts from the JSON API, None for unknown slugs, and raises MotomarksError with the HTTP status and error code for everything else.

The code on this page is the code our CI runs against recorded API responses.

1. Add your keys

Create a key pair in the dashboard. Each key has a publishable pk_ half and a secret sk_ half.
VariableValueUsed for
MOTOMARKS_SECRET_KEYsk_…For get_brand and search_brands
MOTOMARKS_PUBLIC_KEYpk_…For logo_url in HTML and emails

2. Add the code

urllib only, no dependencies. Tested in CI against recorded API responses.

motomarks.py
"""Minimal client for the Motomarks JSON API and image CDN (standard library only).

Use the secret sk_ key for API calls from your server and the publishable
pk_ key in image URLs.
"""

from __future__ import annotations

import json
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Callable

API_BASE = "https://motomarks.io/api/v1"
CDN_BASE = "https://motomarks.io/img"


class MotomarksError(Exception):
    """401 bad key, 403 plan or domain restriction, 404 unknown slug, 429 daily limit."""

    def __init__(self, status: int, code: str, message: str) -> None:
        super().__init__(f"{status} {code}: {message}")
        self.status = status
        self.code = code
        self.message = message


def logo_url(
    slug: str,
    public_key: str,
    *,
    type: str = "full",
    size: str = "md",
    format: str = "webp",
    aspect: str = "square",
) -> str:
    """Image CDN URL. Defaults: full logo, md (256px), WebP, square."""
    params: dict[str, str] = {}
    if type != "full":
        params["type"] = type
    if size != "md":
        params["size"] = size
    if format != "webp":
        params["format"] = format
    if aspect != "square":
        params["aspect"] = aspect
    params["token"] = public_key
    return f"{CDN_BASE}/{urllib.parse.quote(slug)}?{urllib.parse.urlencode(params)}"


def _request(path: str, secret_key: str, opener: Callable[..., Any]) -> dict[str, Any]:
    request = urllib.request.Request(
        f"{API_BASE}{path}",
        headers={"Authorization": f"Bearer {secret_key}", "Accept": "application/json"},
    )
    try:
        with opener(request, timeout=10) as response:
            return json.loads(response.read())
    except urllib.error.HTTPError as error:
        try:
            body = json.loads(error.read() or b"{}")
        except ValueError:
            body = {}
        raise MotomarksError(
            error.code,
            body.get("code") or body.get("error") or "HTTP_ERROR",
            body.get("message") or error.reason,
        ) from None


def get_brand(slug: str, secret_key: str, opener: Callable[..., Any] = urllib.request.urlopen) -> dict[str, Any] | None:
    """One brand by slug, or None when the slug does not exist."""
    try:
        return _request(f"/brands/{urllib.parse.quote(slug)}", secret_key, opener)["data"]
    except MotomarksError as error:
        if error.status == 404:
            return None
        raise


def search_brands(
    query: str,
    secret_key: str,
    *,
    limit: int = 20,
    vehicle_type: str | None = None,
    opener: Callable[..., Any] = urllib.request.urlopen,
) -> list[dict[str, Any]]:
    """Search published brands by name. The API caps `limit` at 100."""
    params = {"q": query, "limit": str(limit)}
    if vehicle_type:
        params["vehicleType"] = vehicle_type
    return _request(f"/brands?{urllib.parse.urlencode(params)}", secret_key, opener)["data"]

Then use it:

app.py
import os
from motomarks import MotomarksError, get_brand, logo_url

brand = get_brand("byd", os.environ["MOTOMARKS_SECRET_KEY"])
if brand:
    src = logo_url(brand["slug"], os.environ["MOTOMARKS_PUBLIC_KEY"], type="badge", size="sm")

3. What the API returns

A real GET /api/v1/brands/byd response, trimmed to the fields these examples use. The full record also carries the description, history, logo evolution, palette and FAQs.
200 GET /api/v1/brands/byd
{
  "data": {
    "id": "a30746ba-3a56-4199-8cc9-af39bfdae8bb",
    "slug": "byd",
    "brandName": "BYD",
    "companyName": "BYD Company Limited",
    "country": "China",
    "parentCompany": null,
    "foundedYear": "1995",
    "officialDomain": "https://www.byd.com",
    "color": "#E60012",
    "colors": [
      "#E60012",
      "#FFFFFF",
      "#000000"
    ],
    "vehicleTypes": [
      "car"
    ],
    "updatedAt": "2026-09-04T04:13:42.072Z"
  }
}

4. Handle every error

Errors are JSON with error and message; 403 and 429 add a machine-readable code. The client turns them into MotomarksError (404 becomes null).

401 · Missing, malformed or revoked key

Fix configuration; do not retry.

401 response
{
  "error": "Unauthorized",
  "message": "API key required. Include 'Authorization: Bearer YOUR_API_KEY' header"
}

403 · Plan inactive, Free plan without a verified attribution link, or a domain-restricted key used elsewhere

Branch on code: SUBSCRIPTION_REQUIRED or DOMAIN_NOT_ALLOWED.

403 response
{
  "error": "Subscription Required",
  "message": "Attribution link required. Add a link to https://motomarks.io on your site and verify it in your dashboard settings.",
  "code": "SUBSCRIPTION_REQUIRED"
}

404 · Slug is not a published brand

Return null and render your fallback.

404 response
{
  "error": "Not Found",
  "message": "Brand not found"
}

429 · Free plan daily request limit reached

Serve cached data; retrying the same day will not succeed.

429 response
{
  "error": "Rate Limit Exceeded",
  "message": "Free plan is limited to 1,000 requests per day. Upgrade your plan for higher limits.",
  "code": "RATE_LIMIT_EXCEEDED"
}

5. Before you ship

Keep sk_ keys on the server
The JSON API takes the secret sk_ key. Call it from a server, route handler or build step, never from browser code. Image URLs use the publishable pk_ key, which is safe in HTML.
Restrict the pk_ key to your domains
Add your production and preview domains to the key in the dashboard. The CDN then refuses requests from other sites, and requests with no Origin or Referer fail closed.
Cache brand data, not just images
Brand records change rarely. Cache API responses for hours or a day and let the CDN cache images; each JSON call counts toward the daily request limit on the Free plan.
Render a fallback for every logo
A revoked key, an unknown slug or a network error should leave the layout intact. Every example falls back to the brand initial at the same size.

Ship Python logos today.

Create a free key, paste it into the variables above, and the examples work as written.

API reference

Free includes 1,000 requests per day with an attribution link. Startup and Pro remove attribution.