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();}// Usageconst 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 levelsconst 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}%`);Find OA, SA and MA Distribution Rates for an Age#
distributionRate gives the share of the total contribution credited to each account. For a 34-year-old:
curl "https://simplycpf.com/api/cpf/age-group/find?age=34"{ "description": "35 and below", "minAge": 0, "maxAge": 35, "contributionRate": { "employee": 0.2, "employer": 0.17 }, "distributionRate": { "OA": 0.6217, "SA": 0.1621, "MA": 0.2162 }}So 62.17% of the total contribution goes to OA, 16.21% to SA and 21.62% to MA. To get dollar amounts for a salary, call POST /calculate with income and age and read distribution.
Python#
Basic Calculation#
import requestsdef 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()# Usageresult = calculate_cpf(5000, age=30)print(f"Employee contribution: ${result['contribution']['employee']}")print(f"Employer contribution: ${result['contribution']['employer']}")Multi-Year Projection#
import requestsdef 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 contributionsprojection = 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 requestsdef 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 optionsresult = 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 };}