chemical equation solver

Chemical Equation
Balancer API

Balance and validate chemical equations programmatically — get step-by-step balancing, reaction coefficients, and element data across a simple REST API. Built for developers.

Try it now Back to Tools

Overview

The Chemical Equation Balancer API balances chemical equations and returns normalized coefficients with step-by-step balancing details. It also validates equation syntax, exposes element metadata (atomic number, mass, group, period), and provides a health check. Every request returns structured JSON with clear error codes.

Base URL & Authentication

Base URL

Base URL

https://odivora.com/api/v1

Authentication

Include your API credentials in every request header.

Headers

X-API-Key: your_api_key
X-API-Secret: your_secret
Content-Type: application/json

Get API Keys

Follow these steps to obtain your API credentials:

1

Log In to Your Account

Existing Users: Go to /login to access your dashboard

New Users: Visit /register to create your free account first

2

Access Your Profile

Once you log in, click on your profile picture in the top-right corner, then click on "Your profile" from the dropdown menu.

3

Create API Key

From your profile page, proceed to the "API Keys" section and create a key by filling in a name you prefer.

Example name

"Bot chem balancer" or "My Chemistry App"

4

Save Your Credentials

Click on "Create API Key" to generate your credentials, then immediately copy and save both the API Key and Secret.

Critical Warning

Your secret key will only be displayed once! Copy it immediately and store it securely. You won't be able to see it again.

Security Notice

Never share your API keys publicly or commit them to version control. Treat them like passwords — regenerate immediately if compromised.

Rate Limits

Free tier: 150 requests/day | Pro tier: 1000 requests/day. Check your dashboard for current usage and limits.

Endpoints

⚖️ Balance EquationPOST /chemical_equation_balancer/balance
✅ Validate EquationPOST /chemical_equation_balancer/validate
🔬 Element InfoGET /chemical_equation_balancer/element_info/<element>
💚 Health CheckGET /chemical_equation_balancer/health

Balance Equation

POST/chemical_equation_balancer/balance

Balances a chemical equation and returns coefficients plus balancing steps.

Request

Request Body

{
  "equation": "CH4 + O2 -> CO2 + H2O"
}

Response

Success Response

{
  "success": true,
  "balanced": true,
  "balanced_equation": "CH4 + 2O2 -> CO2 + 2H2O",
  "elements_found": ["C","H","O"],
  "coefficients": [1,2,1,2],
  "reaction_type": "Redox",
  "reaction_medium": "unspecified",
  "charge_balance": {
    "has_charges": false,
    "reactants": 0,
    "products": 0,
    "conserved": true
  },
  "reactants": [
    {"formula": "CH4", "coefficient": 1, "elements": {"C": 1, "H": 4}, "charge": 0},
    {"formula": "O2", "coefficient": 2, "elements": {"O": 2}, "charge": 0}
  ]
}

Ionic equations conserve charge as well as atoms

// POST /chemical_equation_balancer/balance  {"equation": "Al^3+ + OH- -> Al(OH)3"}
{
  "balanced": true,
  "balanced_equation": "Al^3+ + 3OH- -> Al(OH)3",
  "charge_balance": {"has_charges": true, "reactants": 0, "products": 0, "conserved": true},
  "reactants": [
    {"formula": "Al^3+", "coefficient": 1, "elements": {"Al": 1}, "charge": 3},
    {"formula": "OH-", "coefficient": 3, "elements": {"O": 1, "H": 1}, "charge": -1}
  ],
  "balancing_steps": [
    "... Step 6: Verify the balanced molecular equation | Al (1 = 1), H (3 = 3), O (3 = 3) | Charge: reactants (+3) + 3×(-1) = 0 | products 0 → conserved ✓"
  ]
}

// An equation that balances atoms but not charge comes back with
// "balanced": false, charge_balance.conserved false, and a Step 6 line that says
// which side failed instead of a tick.

Redox equations balance by half-reaction, in acid or in base

// POST /chemical_equation_balancer/balance
//   {"equation": "MnO4- + H2O2 -> MnO2 + OH- + H2O + O2"}
{
  "balanced": true,
  "reaction_type": "Redox (Basic)",
  "reaction_medium": "basic",
  "balanced_equation": "3H2O2 + 2MnO4- -> 2H2O + 2MnO2 + 3O2 + 2OH-",
  "charge_balance": {"has_charges": true, "reactants": -2, "products": -2, "conserved": true},
  "balancing_steps": [
    "... O: -1 → 0 (oxidized, 1e⁻ per atom)",
    "... Mn: 7 → 4 (reduced, 3e⁻ per atom)",
    "... Oxidation (×3): H2O2 + 2OH- → 2H2O + O2 + 2e-",
    "... Reduction (×2): 2H2O + MnO4- + 3e- → MnO2 + 4OH-",
    "... Electrons: 2e⁻ ×3 = 6e⁻ cancelled by 3e⁻ ×2 = 6e⁻",
    "... Combined: 3H2O2 + 2MnO4- -> 2H2O + 2MnO2 + 3O2 + 2OH-",
    "📌 Step 6: Verify the balanced molecular equation | H (6 = 6), Mn (2 = 2), O (14 = 14) | Charge: reactants 2×(-1) = -2 | products 2×(-1) = -2 → conserved ✓"
  ]
}

// Peroxide oxygen is read at -1, not -2, so the electron donor in H2O2 + MnO4- is
// the peroxide itself. The medium comes from the species you write, not from
// whichever balance happens to work: naming the reduced metal as a free cation
// states acid (in base that reduction stops at MnO2), so
//   "MnO4- + H2O2 + H+ -> Mn2+ + O2 + H2O"  and  "H2O2 + MnO4- -> Mn2+ + O2 + H2O"
// both give
//   6H+ + 5H2O2 + 2MnO4- -> 8H2O + 2Mn2+ + 5O2
// and never an alkaline balance, which would put OH- beside the Mn2+ you asked for.
//
// Reaction class and reaction medium are two separate fields. "Redox (Basic)" and
// "reaction_medium": "basic" above are earned by the OH- you wrote; which half-reaction
// route produced the arithmetic earns nothing. So an equation that states no conditions
// comes back with "reaction_type": "Redox" and "reaction_medium": "unspecified" even
// where the balance introduced OH- or H+ itself:
//   {"equation": "C2H5OH + O2 -> CO2 + H2O"}
//   -> "C2H5OH + 3O2 -> 2CO2 + 3H2O", "Redox", "unspecified"   (combustion, not base)
//   {"equation": "MnO4- + H2O2 -> MnO2 + O2 + H2O"}
//   -> "3H2O2 + 2MnO4- -> 2H2O + 2MnO2 + 3O2 + 2OH-", "Redox", "unspecified"
// Write that OH- yourself -- "MnO4- + H2O2 -> MnO2 + OH- + H2O + O2", the example
// above -- and the identical balance is reported as basic.

Failure Response — the API never guesses

// POST /chemical_equation_balancer/balance
//   {"equation": "K2Cr2O7 + H2O2 + H2SO4 -> K2SO4 + Cr2(SO4)3 + O2 + H2O"}
// Written as molecular salts the sulfate spectators cannot travel across a
// half-reaction, and atoms plus charge leave 2 free parameters, so the equation
// is under-determined and none is returned. Balance it ionically instead.
{
  "success": true,
  "balanced": false,
  "balanced_equation": null,
  "coefficients": null,
  "reaction_type": "Redox (half-reaction unresolved)",
  "reaction_medium": "unspecified",
  "verification": {"verified": false, "atoms_conserved": false, "charge_conserved": true},
  "failure": {
    "code": "underdetermined_redox",
    "message": "Atoms and charge leave 2 free parameters, so several equations balance equally well on conservation alone, and the half-reaction method did not resolve the electron transfer. No verified balanced equation is returned.",
    "checks": {"atoms": false, "charge": true, "electron_transfer": "not_established"},
    "mismatched_elements": [{"element": "H", "reactants": 4, "products": 2}, {"element": "O", "reactants": 13, "products": 19}, {"element": "S", "reactants": 1, "products": 4}],
    "charge_balance": {"reactants": 0, "products": 0, "conserved": true, "applicable": false},
    "free_parameters": 2,
    "redox_detected": true,
    "hint": "For a redox equation, give the half-reaction species explicitly (add H+ / OH- / H2O for the medium, or list only the oxidised and reduced pairs) so electron balance can be applied."
  }
}

Verification policy. balanced_equation is populated only when the returned coefficients conserve atoms, conserve net electrical charge, and are valid integers. A redox equation additionally needs electron-transfer consistency: the API builds candidate half-reactions, cancels their electrons, and accepts only a couple that accounts for every species you wrote down and contains no free e-. The medium is not part of that choice: if your species state it (H+, OH-, or a metal written as a free cation such as Mn2+) the other medium is ruled out rather than tried next. Where electron balance cannot be settled, the API reports "balanced": false with a failure object instead of returning a plausible-looking guess.

Labelling policy. reaction_type names the class of reaction and reaction_medium names the conditions, as two separate fields. A medium is claimed only when your own species establish it — H+, OH-, or a metal written both with oxygen and as a free cation — so "Redox (Basic)" never means "the alkaline half-reaction route happened to work". Combustion of ethanol or methane states no conditions and is reported as "Redox" with "unspecified" medium, even where balancing it introduced H+ or OH- as bookkeeping; write those species yourself and the same balance is labelled acidic or basic.

Response model change — 2026-11-05, intentional. Reaction classification and reaction conditions were split into two fields. reaction_medium ("acidic" / "basic" / "unspecified") is new on every Balance Equation response and is the only field that states conditions. reaction_type now returns the bare "Redox" when your input leaves the medium open; the "(Acidic)" / "(Basic)" suffix appears only when your own species establish it, and "Redox (half-reaction unresolved)" on a refusal is unchanged. Integrate against reaction_medium and treat reaction_type as a display label — do not parse it for conditions. balanced_equation, coefficients, reactants, products, verification and charge_balance are untouched by this change, and no other field was added, removed or renamed.

Code Examples

Python

import requests

url = "https://odivora.com/api/v1/chemical_equation_balancer/balance"

headers = {
    "X-API-Key": "your_api_key",
    "X-API-Secret": "your_secret"
}

data = {"equation": "CH4 + O2 -> CO2 + H2O"}

res = requests.post(url, json=data, headers=headers)
print(res.json())

cURL

curl -X POST https://odivora.com/api/v1/chemical_equation_balancer/balance \
-H "X-API-Key: your_api_key" \
-H "X-API-Secret: your_secret" \
-H "Content-Type: application/json" \
-d '{"equation":"CH4 + O2 -> CO2 + H2O"}'

JavaScript

fetch('https://odivora.com/api/v1/chemical_equation_balancer/balance', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'your_api_key',
    'X-API-Secret': 'your_secret'
  },
  body: JSON.stringify({ equation: 'CH4 + O2 -> CO2 + H2O' })
})
.then(res => res.json())
.then(console.log);

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;

public class ChemicalBalancer {
    private static final String BASE_URL = "https://odivora.com/api/v1";
    private static final String API_KEY = "your_api_key";
    private static final String API_SECRET = "your_secret";
    
    private static final HttpClient client = HttpClient.newHttpClient();
    
    public static String balanceEquation(String equation) throws Exception {
        String json = String.format("{\"equation\": \"%s\"}", equation);
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(BASE_URL + "/chemical_equation_balancer/balance"))
            .header("Content-Type", "application/json")
            .header("X-API-Key", API_KEY)
            .header("X-API-Secret", API_SECRET)
            .POST(BodyPublishers.ofString(json))
            .build();
        
        HttpResponse response = client.send(
            request, BodyHandlers.ofString()
        );
        
        return response.body();
    }
    
    public static void main(String[] args) throws Exception {
        String result = balanceEquation("CH4 + O2 -> CO2 + H2O");
        System.out.println(result);
    }
}

Validate Equation

POST/chemical_equation_balancer/validate

Validates chemical equation syntax without balancing.

Request

Request Body

{
  "equation": "H2 + O2 -> H2O"
}

Response

Success Response

{
  "success": true,
  "valid": true,
  "message": "Equation is valid"
}

Code Examples

Python

import requests

url = "https://odivora.com/api/v1/chemical_equation_balancer/validate"

headers = {
    "X-API-Key": "your_api_key",
    "X-API-Secret": "your_secret"
}

data = {"equation": "H2 + O2 -> H2O"}

res = requests.post(url, json=data, headers=headers)
print(res.json())

cURL

curl -X POST https://odivora.com/api/v1/chemical_equation_balancer/validate \
-H "X-API-Key: your_api_key" \
-H "X-API-Secret: your_secret" \
-H "Content-Type: application/json" \
-d '{"equation":"H2 + O2 -> H2O"}'

JavaScript

fetch('https://odivora.com/api/v1/chemical_equation_balancer/validate', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'your_api_key',
    'X-API-Secret': 'your_secret'
  },
  body: JSON.stringify({ equation: 'H2 + O2 -> H2O' })
})
.then(res => res.json())
.then(console.log);

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;

public class ChemicalValidator {
    private static final String BASE_URL = "https://odivora.com/api/v1";
    private static final String API_KEY = "your_api_key";
    private static final String API_SECRET = "your_secret";
    
    private static final HttpClient client = HttpClient.newHttpClient();
    
    public static String validateEquation(String equation) throws Exception {
        String json = String.format("{\"equation\": \"%s\"}", equation);
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(BASE_URL + "/chemical_equation_balancer/validate"))
            .header("Content-Type", "application/json")
            .header("X-API-Key", API_KEY)
            .header("X-API-Secret", API_SECRET)
            .POST(BodyPublishers.ofString(json))
            .build();
        
        HttpResponse response = client.send(
            request, BodyHandlers.ofString()
        );
        
        return response.body();
    }
    
    public static void main(String[] args) throws Exception {
        String result = validateEquation("H2 + O2 -> H2O");
        System.out.println(result);
    }
}

Element Info

GET/chemical_equation_balancer/element_info/<element>

Gets information about a chemical element (name, atomic number, mass, etc.).

Response

Success Response

{
  "name": "Hydrogen",
  "symbol": "H",
  "atomic_number": 1,
  "mass": 1.008,
  "group": 1,
  "period": 1
}

Code Examples

Python

import requests

url = "https://odivora.com/api/v1/chemical_equation_balancer/element_info/H"

headers = {
    "X-API-Key": "your_api_key",
    "X-API-Secret": "your_secret"
}

res = requests.get(url, headers=headers)
print(res.json())

cURL

curl -X GET https://odivora.com/api/v1/chemical_equation_balancer/element_info/H \
-H "X-API-Key: your_api_key" \
-H "X-API-Secret: your_secret"

JavaScript

fetch('https://odivora.com/api/v1/chemical_equation_balancer/element_info/H', {
  method: 'GET',
  headers: {
    'X-API-Key': 'your_api_key',
    'X-API-Secret': 'your_secret'
  }
})
.then(res => res.json())
.then(console.log);

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;

public class ElementInfo {
    private static final String BASE_URL = "https://odivora.com/api/v1";
    private static final String API_KEY = "your_api_key";
    private static final String API_SECRET = "your_secret";
    
    private static final HttpClient client = HttpClient.newHttpClient();
    
    public static String getElementInfo(String element) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(BASE_URL + "/chemical_equation_balancer/element_info/" + element))
            .header("X-API-Key", API_KEY)
            .header("X-API-Secret", API_SECRET)
            .GET()
            .build();
        
        HttpResponse response = client.send(
            request, BodyHandlers.ofString()
        );
        
        return response.body();
    }
    
    public static void main(String[] args) throws Exception {
        String result = getElementInfo("H");
        System.out.println(result);
    }
}

Health Check

GET/chemical_equation_balancer/health

Health check endpoint to verify API status.

Response

Success Response

{
  "success": true,
  "status": "healthy",
  "chemical_equation_balancer_backends": ["default"],
  "max_equation_length": 500
}

Code Examples

Python

import requests

url = "https://odivora.com/api/v1/chemical_equation_balancer/health"

headers = {
    "X-API-Key": "your_api_key",
    "X-API-Secret": "your_secret"
}

res = requests.get(url, headers=headers)
print(res.json())

cURL

curl -X GET https://odivora.com/api/v1/chemical_equation_balancer/health \
-H "X-API-Key: your_api_key" \
-H "X-API-Secret: your_secret"

JavaScript

fetch('https://odivora.com/api/v1/chemical_equation_balancer/health', {
  method: 'GET',
  headers: {
    'X-API-Key': 'your_api_key',
    'X-API-Secret': 'your_secret'
  }
})
.then(res => res.json())
.then(console.log);

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;

public class HealthCheck {
    private static final String BASE_URL = "https://odivora.com/api/v1";
    private static final String API_KEY = "your_api_key";
    private static final String API_SECRET = "your_secret";
    
    private static final HttpClient client = HttpClient.newHttpClient();
    
    public static String checkHealth() throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(BASE_URL + "/chemical_equation_balancer/health"))
            .header("X-API-Key", API_KEY)
            .header("X-API-Secret", API_SECRET)
            .GET()
            .build();
        
        HttpResponse response = client.send(
            request, BodyHandlers.ofString()
        );
        
        return response.body();
    }
    
    public static void main(String[] args) throws Exception {
        String result = checkHealth();
        System.out.println(result);
    }
}

Python SDK

Complete Python SDK with all endpoints and error handling.

Complete SDK Class

import requests
import json

BASE_URL = "https://your-api-domain.com"
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

session = requests.Session()
session.headers.update({
    "Content-Type": "application/json",
    "Accept": "application/json",
    "X-API-Key": API_KEY,
    "X-API-Secret": API_SECRET
})

# --- Health Check ---
def check_health():
    response = session.get(f"{BASE_URL}/api/v1/chemical_equation_balancer/health")
    return response.json()

# --- Validate Equation ---
def validate_equation(equation):
    response = session.post(
        f"{BASE_URL}/api/v1/chemical_equation_balancer/validate",
        json={"equation": equation}
    )
    return response.json()

# --- Balance Equation ---
def balance_equation(equation):
    response = session.post(
        f"{BASE_URL}/api/v1/chemical_equation_balancer/balance",
        json={"equation": equation}
    )
    
    if response.status_code == 200:
        result = response.json()
        if result['success']:
            return {
                'balanced': result['balanced_equation'],
                'elements': result['elements_found'],
                'steps': result['balancing_steps'],
                'coefficients': result['coefficients']
            }
    return None

# --- Get Element Information ---
def get_element_info(element):
    response = session.get(
        f"{BASE_URL}/api/v1/chemical_equation_balancer/element_info/{element}"
    )
    return response.json()

# --- Test All Endpoints ---
def test_chemical_api():
    print("=== Chemical Equation Balancer API Test ===")
    
    # Health check
    health = check_health()
    print(f"Health: {health.get('status', 'unknown')}")
    
    # Test equations
    equations = [
        "H2 + O2 -> H2O",
        "CH4 + O2 -> CO2 + H2O",
        "Fe + O2 -> Fe2O3",
        "KMnO4 + HCl -> KCl + MnCl2 + Cl2 + H2O"
    ]
    
    for equation in equations:
        print(f"\nTesting: {equation}")
        
        # Validate
        validation = validate_equation(equation)
        print(f"Valid: {validation.get('valid', False)}")
        
        # Balance
        result = balance_equation(equation)
        if result:
            print(f"Balanced: {result['balanced']}")
            print(f"Elements: {', '.join(result['elements'])}")
        else:
            print("Balancing failed")
    
    # Test element info
    elements = ["H", "O", "C", "Fe", "Au"]
    for element in elements:
        info = get_element_info(element)
        # API returns element data directly, not wrapped in success/element_info
        if 'name' in info and info['name'] != 'Unknown':
            print(f"{element}: {info['name']} (#{info['atomic_number']})")
        else:
            print(f"{element}: Unknown element")

if __name__ == "__main__":
    test_chemical_api()

Errors & Status Codes

Error Response Format

Error Response

{
  "success": false,
  "error": {
    "code": 400,
    "message": "Invalid equation syntax"
  }
}

Status Codes

Rate Limits

Per-minute limit: 100 requests/minute per API key
Free tier: 150 requests/day
Pro tier: 1,000 requests/day
Max equation length: 500 characters