BloodwebMicroservices Sign in
← Colour converter

Convert HEX, RGB and HSL colours in Python

Convert a colour between hex, RGB, HSL, HSV, CMYK and CIE Lab, find its nearest CSS name, and check WCAG contrast against another colour. Here is the whole call in Python, with the output it produced when we ran it.

Before you start

The code

Save it as color-convert.py and run python3 color-convert.py.

import os

import requests

resp = requests.get(
    "https://bloodweb.net/api/v1/color-convert",
    headers={"Authorization": f"Bearer {os.environ['BLOODWEB_KEY']}"},
    params={"color": "#c0392b", "contrast_with": "white"},
    timeout=120,
)
if not resp.ok:
    raise SystemExit(f"{resp.status_code}: {resp.json()['error']['message']}")
print(resp.json())

What you get

Tested 19 October 2026: this exact code ran against our test copy of the API, which runs the same service code as bloodweb.net, and produced this.

The API answers with JSON, which Python prints as a dictionary:

{
    "hex": "#c0392b",
    "hex8": null,
    "rgb": {
        "r": 192,
        "g": 57,
        "b": 43,
        "a": 1
    },
    "rgb_css": "rgb(192, 57, 43)",
    "hsl": {
        "h": 5.6,
        "s": 63.4,
        "l": 46.1
    },
    "hsl_css": "hsl(5.6, 63.4%, 46.1%)",
    "hsv": {
        "h": 5.6,
        "s": 77.6,
        "v": 75.3
    },
    "cmyk": {
        "c": 0,
        "m": 70.3,
        "y": 77.6,
        "k": 24.7
    },
    "lab": {
        "l": 44.68,
        "a": 52.91,
        "b": 39.24
    },
    "name": null,
    "nearest_name": "firebrick",
    "luminance": 0.1431,
    "best_text": "#ffffff",
    "contrast": {
        "with": "#ffffff",
        "ratio": 5.43,
        "aa_normal": true,
        "aa_large": true,
        "aaa_normal": false,
        "aaa_large": true
    }
}

Change the call

Every option the Colour converter takes. Add or change them the same way as the ones in the code.

If it fails

A failed call is not charged. The answer is JSON with an error object; the code above prints its message. The usual ones:

Every code and its fix is in the docs.

Next