If you're building a fintech app that serves Muslim investors — or adding Shariah compliance features to an existing platform — the Halal Terminal API lets you integrate stock screening, ETF analysis, purification calculations, and zakat in minutes. This tutorial shows you how with Python, JavaScript, and React examples.

Getting Started

1. Get Your API Key

curl -X POST https://api.halalterminal.com/api/keys/generate \
  -H "Content-Type: application/json" \
  -d '{"email": "dev@yourapp.com"}'

You'll receive a free API key with 50 calls/month instantly. No credit card required.

2. Test the Connection

curl https://api.halalterminal.com/api/health

Python Integration

Basic Stock Screening

import requests

class HalalTerminal:
    BASE_URL = "https://api.halalterminal.com/api"

    def __init__(self, api_key: str):
        self.session = requests.Session()
        self.session.headers["X-API-Key"] = api_key

    def screen_stock(self, symbol: str) -> dict:
        resp = self.session.post(f"{self.BASE_URL}/screen/{symbol}")
        resp.raise_for_status()
        return resp.json()

    def screen_etf(self, symbol: str) -> dict:
        resp = self.session.post(f"{self.BASE_URL}/etf/{symbol}/screen")
        resp.raise_for_status()
        return resp.json()

    def calculate_zakat(self, holdings: list, gold_price: float = 65.0) -> dict:
        resp = self.session.post(
            f"{self.BASE_URL}/zakat/calculate",
            json={"holdings": holdings, "gold_price_per_gram": gold_price}
        )
        resp.raise_for_status()
        return resp.json()

# Usage
api = HalalTerminal("YOUR_KEY")
result = api.screen_stock("AAPL")

if result["is_compliant"]:
    print(f"AAPL is halal (purification: {result['purification_rate']:.1%})")
else:
    print("AAPL fails Shariah screening")

Portfolio Compliance Check

def check_portfolio(api, symbols):
    results = []
    for symbol in symbols:
        data = api.screen_stock(symbol)
        results.append({
            "symbol": symbol,
            "compliant": data["is_compliant"],
            "aaoifi": data["aaoifi_compliant"],
            "djim": data["djim_compliant"],
            "purification": data["purification_rate"],
        })
    return results

portfolio = check_portfolio(api, ["AAPL", "MSFT", "NVDA", "GOOGL", "AMZN"])
compliant = [r for r in portfolio if r["compliant"]]
print(f"Portfolio compliance: {len(compliant)}/{len(portfolio)} stocks pass")

JavaScript / Node.js Integration

class HalalTerminal {
  constructor(apiKey) {
    this.baseUrl = 'https://api.halalterminal.com/api';
    this.headers = {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json'
    };
  }

  async screenStock(symbol) {
    const resp = await fetch(
      `${this.baseUrl}/screen/${symbol}`,
      { method: 'POST', headers: this.headers }
    );
    return resp.json();
  }

  async screenETF(symbol) {
    const resp = await fetch(
      `${this.baseUrl}/etf/${symbol}/screen`,
      { method: 'POST', headers: this.headers }
    );
    return resp.json();
  }

  async calculateZakat(holdings) {
    const resp = await fetch(
      `${this.baseUrl}/zakat/calculate`,
      {
        method: 'POST',
        headers: this.headers,
        body: JSON.stringify({ holdings, gold_price_per_gram: 65.0 })
      }
    );
    return resp.json();
  }
}

// Usage
const api = new HalalTerminal('YOUR_KEY');
const result = await api.screenStock('NVDA');
console.log(`NVDA: ${result.is_compliant ? 'HALAL' : 'NOT COMPLIANT'}`);

React Component Example

import { useState } from 'react';

function StockScreener({ apiKey }) {
  const [symbol, setSymbol] = useState('');
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);

  const screenStock = async () => {
    setLoading(true);
    const resp = await fetch(
      `https://api.halalterminal.com/api/screen/${symbol}`,
      {
        method: 'POST',
        headers: { 'X-API-Key': apiKey }
      }
    );
    setResult(await resp.json());
    setLoading(false);
  };

  return (
    <div>
      <input
        value={symbol}
        onChange={e => setSymbol(e.target.value.toUpperCase())}
        placeholder="Enter ticker (e.g. AAPL)"
      />
      <button onClick={screenStock} disabled={loading}>
        {loading ? 'Screening...' : 'Screen Stock'}
      </button>

      {result && (
        <div>
          <h3>{result.symbol}: {result.is_compliant ? 'HALAL' : 'NOT COMPLIANT'}</h3>
          <table>
            <tbody>
              <tr><td>AAOIFI</td><td>{result.aaoifi_compliant ? 'PASS' : 'FAIL'}</td></tr>
              <tr><td>DJIM</td><td>{result.djim_compliant ? 'PASS' : 'FAIL'}</td></tr>
              <tr><td>FTSE</td><td>{result.ftse_compliant ? 'PASS' : 'FAIL'}</td></tr>
              <tr><td>MSCI</td><td>{result.msci_compliant ? 'PASS' : 'FAIL'}</td></tr>
              <tr><td>S&P</td><td>{result.sp_compliant ? 'PASS' : 'FAIL'}</td></tr>
              <tr><td>Purification</td><td>{(result.purification_rate * 100).toFixed(1)}%</td></tr>
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

Error Handling

# Always handle API errors gracefully
import requests

def safe_screen(api_key, symbol):
    try:
        resp = requests.post(
            f"https://api.halalterminal.com/api/screen/{symbol}",
            headers={"X-API-Key": api_key},
            timeout=30
        )
        if resp.status_code == 401:
            raise ValueError("Invalid API key")
        if resp.status_code == 429:
            raise ValueError("Rate limit exceeded — upgrade your plan")
        if resp.status_code == 404:
            return {"error": f"Symbol {symbol} not found"}
        resp.raise_for_status()
        return resp.json()
    except requests.Timeout:
        return {"error": "Request timed out — try again"}
    except requests.RequestException as e:
        return {"error": str(e)}

Build with Halal Terminal

Halal Terminal API

58+ endpoints, 5 screening methodologies, ETF analysis, zakat calculators, and MCP tools. Free tier available.

Key Takeaways

Important Disclaimer

Not financial advice. The information provided on this page is for educational and informational purposes only and should not be construed as financial advice, investment advice, trading advice, or any other type of advice. You should not make any financial decisions based solely on the information presented here.

Not a fatwa. Shariah compliance screening results are generated using automated data analysis based on publicly available financial data. These results do not constitute a religious ruling (fatwa) and should not be treated as one. Always consult a qualified Islamic scholar or Shariah advisor for guidance specific to your situation.

Do your own research. Past performance and current compliance status do not guarantee future results or continued compliance. Screening data may contain errors or become outdated. Always verify information independently and consult with a qualified financial advisor before making any investment decisions.