"""Thin client for https://indianfirmdata.com. Standard library only (urllib, json, hmac).""" from __future__ import annotations import hashlib import hmac import json import os import urllib.error import urllib.parse import urllib.request from typing import Any, Dict, Iterable, List, Mapping, Optional, Union DEFAULT_BASE_URL = "https://indianfirmdata.com" USER_AGENT = "indianfirmdata-python/0.1.0" Filters = Union[Mapping[str, Any], List[Mapping[str, Any]]] class IndianFirmDataError(Exception): """An API error. `status` is the HTTP status, `code` the API error code (for example `unauthorized`, `rate_limited`, `top_up_needed`, `bad_request`, `not_found`).""" def __init__(self, status: int, code: str, message: str, body: Optional[dict] = None): super().__init__(f"{status} {code}: {message}") self.status = status self.code = code self.message = message self.body = body or {} class IndianFirmData: """Client for the IndianFirmData REST API. Every call returns the parsed JSON response: ``{"data": ..., "meta": {"request_id", "credits_charged", "balance"}}``. Pass ``dry_run=True`` to any method to see the credit cost without being charged. """ def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, timeout: float = 30.0): self.api_key = api_key or os.environ.get("IFD_API_KEY", "") self.base_url = (base_url or os.environ.get("IFD_API_URL") or DEFAULT_BASE_URL).rstrip("/") self.timeout = timeout # ---------- transport ---------- def request(self, method: str, path: str, params: Optional[Mapping[str, Any]] = None, body: Any = None, dry_run: bool = False) -> Dict[str, Any]: q = {k: v for k, v in (params or {}).items() if v is not None and v != ""} if dry_run: q["dry_run"] = "true" url = self.base_url + path + (("?" + urllib.parse.urlencode(q)) if q else "") headers = {"accept": "application/json", "user-agent": USER_AGENT} if self.api_key: headers["authorization"] = f"Bearer {self.api_key}" data = None if body is not None: data = json.dumps(body).encode("utf-8") headers["content-type"] = "application/json" req = urllib.request.Request(url, data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=self.timeout) as res: text = res.read().decode("utf-8") return json.loads(text) if text else {} except urllib.error.HTTPError as e: text = e.read().decode("utf-8", "replace") try: j = json.loads(text) except ValueError: j = {} err = j.get("error") if isinstance(j, dict) else None if isinstance(err, dict): raise IndianFirmDataError(e.code, str(err.get("code", "error")), str(err.get("message", "")), j) from None raise IndianFirmDataError(e.code, "http_error", text[:200], j if isinstance(j, dict) else None) from None def _get(self, path: str, dry_run: bool = False, **params: Any) -> Dict[str, Any]: return self.request("GET", path, params=params, dry_run=dry_run) def _post(self, path: str, body: Any, dry_run: bool = False) -> Dict[str, Any]: return self.request("POST", path, body=body, dry_run=dry_run) # ---------- companies ---------- def filters(self) -> Dict[str, Any]: """Every search filter field with its type and operators. Free.""" return self._get("/api/v1/filters") def search(self, filters: Optional[Filters] = None, q: Optional[str] = None, sort: Optional[str] = None, limit: Optional[int] = None, offset: Optional[int] = None, dry_run: bool = False) -> Dict[str, Any]: """Structured company search. 0.01 credits per result. ``filters`` is shorthand ``{"state": "Karnataka", "employee_count": {"gte": 100}}`` or a list of ``{"field", "op", "value"}``. ``sort``: relevance, name, employees, newest, oldest, hiring, updated. """ body = {k: v for k, v in {"q": q, "filters": filters, "sort": sort, "limit": limit, "offset": offset}.items() if v is not None} return self._post("/api/v1/companies/search", body, dry_run) def nl_search(self, query: str, limit: Optional[int] = None, dry_run: bool = False) -> Dict[str, Any]: """Plain-English search, e.g. "listed IT companies in Pune". 0.5 credits + 0.01 per result.""" body: Dict[str, Any] = {"query": query} if limit is not None: body["limit"] = limit return self._post("/api/v1/companies/nl-search", body, dry_run) def enrich(self, domain: Optional[str] = None, name: Optional[str] = None, cin: Optional[str] = None, lei: Optional[str] = None, isin: Optional[str] = None, nse: Optional[str] = None, wikidata: Optional[str] = None, state: Optional[str] = None, min_confidence: Optional[float] = None, include: Optional[Iterable[str]] = None, dry_run: bool = False) -> Dict[str, Any]: """Resolve one company by domain, name, CIN, LEI, ISIN, NSE symbol or Wikidata id and return its full profile with sources and freshness. 1 credit on a match, 0 on no match.""" return self._get( "/api/v1/companies/enrich", dry_run, domain=domain, name=name, cin=cin, lei=lei, isin=isin, nse=nse, wikidata=wikidata, state=state, min_confidence=min_confidence, include=",".join(include) if include else None, ) def company(self, company_id: str, include_people: bool = False, dry_run: bool = False) -> Dict[str, Any]: """Profile by company id (``co_...``). 1 credit (+0.5 per person with include_people).""" return self._get(f"/api/v1/companies/{urllib.parse.quote(company_id)}", dry_run, include="people" if include_people else None) def people(self, company_id: str, dry_run: bool = False) -> Dict[str, Any]: """Officers and founders from public business sources (no personal contact data). 0.5 credits per person.""" return self._get(f"/api/v1/companies/{urllib.parse.quote(company_id)}/people", dry_run) def jobs(self, company_id: str, live: bool = False, dry_run: bool = False) -> Dict[str, Any]: """Job posts and hiring signals (beta).""" return self._get(f"/api/v1/companies/{urllib.parse.quote(company_id)}/jobs", dry_run, live="1" if live else None) def news(self, company_id: str, live: bool = False, dry_run: bool = False) -> Dict[str, Any]: """News and funding events (beta).""" return self._get(f"/api/v1/companies/{urllib.parse.quote(company_id)}/news", dry_run, live="1" if live else None) def techstack(self, company_id: str, live: bool = False, dry_run: bool = False) -> Dict[str, Any]: """Technologies detected on the company website (beta).""" return self._get(f"/api/v1/companies/{urllib.parse.quote(company_id)}/techstack", dry_run, live="1" if live else None) # ---------- identifiers ---------- def decode(self, value: str) -> Dict[str, Any]: """Validate and decode a CIN, GSTIN (state, PAN, check digit), PAN, Udyam, LEI or ISIN. Free.""" return self._get("/api/v1/identifiers/decode", value=value) # ---------- bulk, watchers, usage ---------- def export(self, filters: Optional[Filters] = None, q: Optional[str] = None, format: str = "json", max_rows: Optional[int] = None, dry_run: bool = False) -> Dict[str, Any]: """Export every company matching a search as JSON or CSV (max 50,000 rows). 0.005 credits per row.""" search = {k: v for k, v in {"q": q, "filters": filters}.items() if v is not None} body: Dict[str, Any] = {"search": search, "format": format} if max_rows is not None: body["max_rows"] = max_rows return self._post("/api/v1/datasets/export", body, dry_run) def create_watcher(self, kind: str, company_ids: Optional[List[str]] = None, filters: Any = None, fields: Optional[List[str]] = None, webhook_url: Optional[str] = None) -> Dict[str, Any]: """Watch companies for changes (``kind="company"``) or a saved search for new matches (``kind="search"``).""" body = {k: v for k, v in {"kind": kind, "company_ids": company_ids, "filters": filters, "fields": fields, "webhook_url": webhook_url}.items() if v is not None} return self._post("/api/v1/watchers", body) def list_watchers(self) -> Dict[str, Any]: return self._get("/api/v1/watchers") def delete_watcher(self, watcher_id: str) -> Dict[str, Any]: return self.request("DELETE", f"/api/v1/watchers/{urllib.parse.quote(watcher_id)}") def usage(self) -> Dict[str, Any]: """Credit balance and usage for the last 30 days. Free.""" return self._get("/api/v1/usage") def verify_webhook(secret: str, timestamp: str, raw_body: Union[str, bytes], signature: str) -> bool: """Check a watcher webhook: header ``x-surge-signature`` is ``v1=``.""" body = raw_body.decode("utf-8") if isinstance(raw_body, bytes) else raw_body expected = "v1=" + hmac.new(secret.encode("utf-8"), f"{timestamp}.{body}".encode("utf-8"), hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature)