madeenan

Python Integration Guide

Build a Cited Islamic Assistant With Python

A practical Python integration with timeouts, error handling, source normalization, and visible citations.

What You Will Build

A small Python service that retrieves sources safely and returns a clean list your application can display or send to its own model provider.

Prerequisites

  • Python 3.11 or newer
  • requests
  • A Madeenan API key stored in the environment
  • A backend or command-line application

Retrieve Sources With a Timeout

Send the user's topic to the Search API and request only the indexes your product needs. Always set a timeout so an upstream delay cannot hold your worker indefinitely.

import os
import requests
def search_sources(question: str) -> dict:
response = requests.get(
"https://api.madeenan.com/v1/search",
headers={"X-Madeenan-API-Key": os.environ["MADEENAN_API_KEY"]},
params={
"q": question,
"indexes": "quran,hadith,tafsir,dua",
"limit_per_source": 4,
},
timeout=20,
)
response.raise_for_status()
return response.json()

Flatten Results Without Losing Metadata

Keep the source type and reference with every item. Removing those fields makes it difficult to render a useful citation or audit what supported an answer.

def readable_sources(payload: dict) -> list[dict]:
sources = []
for source_type, items in payload.get("results", {}).items():
for item in items:
if not item.get("arabic") and not item.get("translation"):
continue
sources.append({
"type": source_type,
"ref": item.get("ref"),
"arabic": item.get("arabic"),
"translation": item.get("translation"),
"grade": item.get("grade"),
})
return sources

Fail Closed When Sources Are Missing

If the source list is empty, return a retrieval message instead of asking a model to improvise. Catch timeout, authentication, and rate-limit failures separately so the caller knows whether to retry.

Security Boundary

Load the key from the process environment or a secret manager. Do not commit it to a repository, notebook, mobile build, or browser bundle.

Test Before Shipping

  • Mock a successful search response
  • Mock a timeout
  • Mock 401 and 429 responses
  • Drop items with no readable text
  • Preserve Hadith grades and references