API Documentation

Examples

Code examples for common use cases

Practical examples for integrating the CPF API into your applications.

JavaScript / TypeScript

Calculate Monthly Contribution

async function calculateCpfContribution(income: number, age?: number) {
  const response = await fetch(
    "https://simplycpf.com/api/cpf/calculate",
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ income, age }),
    }
  );

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error);
  }

  return response.json();
}

// Usage
const result = await calculateCpfContribution(5000, 30);
console.log(`Take-home pay: $${result.afterCpfContribution}`);

Batch Processing

async function batchCalculate(incomes: number[]) {
  const scenarios = incomes.map((income) => ({ income }));

  const response = await fetch(
    "https://simplycpf.com/api/cpf/calculate/batch",
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ scenarios }),
    }
  );

  return response.json();
}

// Calculate for multiple income levels
const results = await batchCalculate([4000, 5000, 6000, 7000, 8000]);

Get Age-Appropriate Rates

async function getAgeGroupRates(age: number) {
  const response = await fetch(
    `https://simplycpf.com/api/cpf/age-group/find?age=${age}`
  );

  return response.json();
}

const rates = await getAgeGroupRates(45);
console.log(`Employee rate: ${rates.contributionRate.employee * 100}%`);

Python

Basic Calculation

import requests

def calculate_cpf(income: float, age: int = None) -> dict:
    payload = {"income": income}
    if age:
        payload["age"] = age

    response = requests.post(
        "https://simplycpf.com/api/cpf/calculate",
        json=payload
    )
    response.raise_for_status()
    return response.json()

# Usage
result = calculate_cpf(5000, age=30)
print(f"Employee contribution: ${result['contribution']['employee']}")
print(f"Employer contribution: ${result['contribution']['employer']}")

Multi-Year Projection

import requests

def project_cpf(income: float, age: int, years: int) -> dict:
    response = requests.post(
        "https://simplycpf.com/api/cpf/projection",
        json={"income": income, "age": age, "years": years}
    )
    response.raise_for_status()
    return response.json()

# Project 10 years of contributions
projection = project_cpf(6000, 30, 10)

for year_data in projection["projections"]:
    print(f"Year {year_data['year']}: "
          f"Cumulative total: ${year_data['cumulative']['totalContribution']:,.2f}")

Compare Investment Returns

import requests

def compare_investments(principal: float, years: int, scenarios: list) -> dict:
    response = requests.post(
        "https://simplycpf.com/api/cpf/investment-comparison",
        json={
            "principal": principal,
            "years": years,
            "scenarios": scenarios
        }
    )
    response.raise_for_status()
    return response.json()

# Compare different investment options
result = compare_investments(
    principal=100000,
    years=20,
    scenarios=[
        {"name": "CPF OA (2.5%)", "rate": 2.5},
        {"name": "CPF SA (4.0%)", "rate": 4.0},
        {"name": "Index Fund (7%)", "rate": 7.0}
    ]
)

for r in result["results"]:
    print(f"{r['name']}: ${r['finalValue']:,.2f} (+{r['growthPercentage']:.1f}%)")

React Hook

import { useState, useCallback } from "react";

interface CpfResult {
  contribution: {
    employee: number;
    employer: number;
    totalContribution: number;
  };
  distribution: {
    OA: number;
    SA: number;
    MA: number;
  };
  afterCpfContribution: number;
}

export function useCpfCalculator() {
  const [result, setResult] = useState<CpfResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const calculate = useCallback(async (income: number, age?: number) => {
    setLoading(true);
    setError(null);

    try {
      const response = await fetch(
        "https://simplycpf.com/api/cpf/calculate",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ income, age }),
        }
      );

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error);
      }

      const data = await response.json();
      setResult(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  }, []);

  return { result, loading, error, calculate };
}

On this page