What you will have in five minutes
An API key stored safely in an environment variable, a working request in the language you prefer, a clear picture of what comes back, and error handling for the three surprises that catch most first-time users. Every command and script below was run against the live API; the output shown is real, shortened where noted. Prices move, so your numbers will differ.
The short version, if you already have a key:
export INDIANAPI_KEY="YOUR_API_KEY"
curl --silent --get "https://stock.indianapi.in/stock" \
--data-urlencode "name=Tata Consultancy Services" \
--header "X-Api-Key: $INDIANAPI_KEY" | jq '{company: .companyName, nse: .currentPrice.NSE}'
{
"company": "Tata Consultancy Services",
"nse": "2407.50"
}
If that printed a company and a price, you are done with setup. The rest of this guide explains each piece and what to do when it does not.
Before you start
You need a free account at indianapi.in and a terminal. Then pick one client:
| Client | Version | Notes |
|---|---|---|
curl | any recent | Add jq to read JSON comfortably |
| Python | 3.8 or later | Standard library only, no pip install |
| Node.js | 18 or later | Built-in fetch, no dependencies |
1. Get your key and keep it out of your code
Sign up for free and you get 500 API credits to start with. Then copy the API key from your dashboard. The dashboard labels can change, so follow the current interface rather than a menu name.
Put the key in an environment variable for this terminal session:
export INDIANAPI_KEY="YOUR_API_KEY"
Confirm it is set without printing it:
if [ -n "$INDIANAPI_KEY" ]; then echo "Key is set"; else echo "Key is missing"; fi
Key is set
Treat the key like a password. Do not paste it into a public repository, browser code, a screenshot or a support post. For a project, keep it in a .env file that is listed in .gitignore, and rotate the key from your dashboard if it is ever exposed. Requests are authenticated with a single header, X-Api-Key.
2. Pick the host for your plan
The host depends on your subscription. A valid key sent to the wrong plan's host can fail, so match them.
| Plan | Base URL | API credits | What you get |
|---|---|---|---|
| Free | https://stock.indianapi.in | 500 | The core endpoints, free on sign-up |
| Hobby | https://stock.indianapi.in | 5,000 | The same endpoints as Free, with more credits and higher rate limits |
| Developer | https://dev.indianapi.in | 10,000 | Additional endpoints on a dedicated server |
| Growth Analyst | https://analyst.indianapi.in | 50,000 | Additional endpoints on a dedicated server |
| Pro | https://pro.indianapi.in | 100,000 | Additional endpoints on a dedicated server |
The examples below use the Free/Hobby host. If you are on Developer, Growth Analyst or Pro, change BASE_URL and nothing else. Those plans unlock additional endpoints (batch quotes, indices, usage and more) that the Free/Hobby host returns Endpoint not allowed for, so check the endpoints your project depends on before you pick a plan.
3. Your first request with curl
BASE_URL="https://stock.indianapi.in"
curl --fail-with-body --silent --show-error \
--get "$BASE_URL/stock" \
--data-urlencode "name=Tata Consultancy Services" \
--header "X-Api-Key: $INDIANAPI_KEY" \
--header "Accept: application/json"
Run that bare and your terminal fills with JSON. The /stock response for a large company was about 445 KB across 21 top-level fields, mostly financial statements. That is plenty of data, but it is not a good first thing to scroll through. Pipe it through jq and pick what you want:
curl --fail-with-body --silent --show-error \
--get "$BASE_URL/stock" \
--data-urlencode "name=Tata Consultancy Services" \
--header "X-Api-Key: $INDIANAPI_KEY" \
--header "Accept: application/json" \
| jq '{company: .companyName, industry, nse: .currentPrice.NSE, bse: .currentPrice.BSE,
change_pct: .percentChange, year_high: .yearHigh, year_low: .yearLow}'
{
"company": "Tata Consultancy Services",
"industry": "Software & Programming",
"nse": "2407.50",
"bse": "2410.00",
"change_pct": "-0.76",
"year_high": "3336.70",
"year_low": "1976.00"
}
--data-urlencode handles the spaces in the company name, and --fail-with-body makes curl exit non-zero on an HTTP error while still showing the server's message. You can look a company up by name or by symbol: both name=TCS and symbol=TCS returned the same company in testing.
4. The same call in Python
Save this as first_call.py. It uses only the standard library:
import json
import os
import sys
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
BASE_URL = "https://stock.indianapi.in" # change for your plan
name = sys.argv[1] if len(sys.argv) > 1 else "Tata Consultancy Services"
request = Request(
f"{BASE_URL}/stock?{urlencode({'name': name})}",
headers={"X-Api-Key": os.environ.get("INDIANAPI_KEY", ""), "Accept": "application/json"},
)
try:
with urlopen(request, timeout=20) as response:
data = json.load(response)
except HTTPError as err:
# Auth and plan errors come back as plain text, not JSON.
sys.exit(f"HTTP {err.code}: {err.read().decode().strip()}")
# Some failures (unknown company, missing parameter) are HTTP 200 with an "error" key.
if "error" in data:
sys.exit(f"API error: {data['error']}")
# Prices and percentages are strings in this response; convert before doing maths.
nse = float(data["currentPrice"]["NSE"])
change = float(data["percentChange"])
print(f"{data['companyName']} ({data['industry']})")
print(f"NSE price: Rs {nse:,.2f} ({change:+.2f}%)")
print(f"52-week: Rs {float(data['yearLow']):,.2f} - Rs {float(data['yearHigh']):,.2f}")
print(f"Top-level fields: {len(data)}")
python3 first_call.py
Tata Consultancy Services (Software & Programming)
NSE price: Rs 2,407.50 (-0.76%)
52-week: Rs 1,976.00 - Rs 3,336.70
Top-level fields: 21
Pass another company as an argument, for example python3 first_call.py "Infosys". The two comments in the script are not decoration; they cover the two behaviours that surprise people most, explained in the errors section below.
5. The same call in Node.js
Save this as first_call.mjs. The .mjs extension lets you use top-level await without any project setup:
const BASE_URL = "https://stock.indianapi.in"; // change for your plan
const name = process.argv[2] ?? "Tata Consultancy Services";
const url = new URL("/stock", BASE_URL);
url.searchParams.set("name", name);
const response = await fetch(url, {
headers: { "X-Api-Key": process.env.INDIANAPI_KEY ?? "", Accept: "application/json" },
signal: AbortSignal.timeout(20_000),
});
if (!response.ok) {
// Auth and plan errors come back as plain text, not JSON.
console.error(`HTTP ${response.status}: ${(await response.text()).trim()}`);
process.exit(1);
}
const data = await response.json();
// Some failures (unknown company, missing parameter) are HTTP 200 with an "error" key.
if (data.error) {
console.error(`API error: ${data.error}`);
process.exit(1);
}
// Prices and percentages are strings in this response; convert before doing maths.
const nse = Number(data.currentPrice.NSE);
const change = Number(data.percentChange);
const inr = (n) => n.toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
console.log(`${data.companyName} (${data.industry})`);
console.log(`NSE price: Rs ${inr(nse)} (${change >= 0 ? "+" : ""}${change.toFixed(2)}%)`);
console.log(`52-week: Rs ${inr(Number(data.yearLow))} - Rs ${inr(Number(data.yearHigh))}`);
console.log(`Top-level fields: ${Object.keys(data).length}`);
node first_call.mjs
Tata Consultancy Services (Software & Programming)
NSE price: Rs 2,407.50 (-0.76%)
52-week: Rs 1,976.00 - Rs 3,336.70
Top-level fields: 21
The AbortSignal.timeout line matters in real code: without a timeout, a stalled connection can hang your process indefinitely. Avoid logging request headers, since they contain your key.
6. What is in the response
The /stock response is one large object. These are the fields from the TCS response above, grouped by what you would use them for:
| Field | Type | What it holds |
|---|---|---|
companyName, industry | string | Name and sector |
currentPrice | object | Latest price per exchange, as BSE and NSE |
percentChange, yearHigh, yearLow | string | Day change and 52-week range |
stockTechnicalData | array | Moving-average prices for several day windows |
keyMetrics | object | Valuation, margins, growth and other ratio groups |
analystView, recosBar | array, object | Analyst rating counts and their trend |
riskMeter | object | A risk category and standard deviation |
shareholding | array | Promoter and other holder categories |
stockCorporateActionData | object | Dividends, bonuses and other actions |
recentNews | array | Recent headlines with summaries and URLs |
companyProfile | object | Description, officers and peer companies |
financials, stockFinancialData | array | Full financial statements, about 209 KB each |
Four things worth knowing before you build on it:
- Numbers are strings.
currentPrice.NSEis"2407.50", not2407.5. Convert withfloat()orNumber()before comparing or adding. - It is heavy. The two financial fields alone are around 417 KB, and in our test
financialsandstockFinancialDatawere identical. Pick the fields you need and do not forward the whole payload to a browser. - Some fields can be
null.futureExpiryDates,futureOverviewDataandinitialStockFinancialDatawerenullfor TCS. Guard before you index into a field. - The schema can change. Build on fields you have confirmed in a live response, and keep parsing code tolerant of additions.
7. Try another endpoint
Once /stock works, the lighter endpoints are a good way to see other shapes. These take no parameters:
curl --fail-with-body --silent --show-error "$BASE_URL/trending" \
--header "X-Api-Key: $INDIANAPI_KEY" \
| jq -r '.trending_stocks.top_gainers[:3][] | "\(.company_name) \(.price) +\(.percent_change)%"'
Hitachi Energy India 31610 +10.72%
Amber Enterprises India 6760 +8.77%
ITI 266.55 +6.17%
/NSE_most_active returns an array of the most active NSE stocks, and /ipo returns IPO data, including recently listed issues. Each endpoint has its own response shape, so print one before you write parsing code for it. Which endpoints your key can call depends on your plan.
8. Errors you will actually see
This is the part most quickstarts skip. We sent deliberately bad requests to the live API and recorded what came back:
| What you did | HTTP status | Body |
|---|---|---|
No X-Api-Key header | 400 | Missing API key (plain text) |
| A wrong or revoked key | 401 | Invalid API key (plain text) |
/stock with a company that does not exist | 200 | {"error": "Stock not found"} |
/stock with no name or symbol | 200 | {"error": "Please provide either name, symbol or id"} |
| An endpoint your plan cannot use | 404 | Endpoint not allowed. Check if the endpoint is valid. (plain text) |
| POST to a GET endpoint | 405 | {"detail": "Method Not Allowed"} |
Three lessons fall out of that table:
- A 200 does not mean success. Unknown companies and missing parameters return HTTP 200 with an
errorkey. Checking onlyresponse.okwill treat{"error": "Stock not found"}as good data and then crash two lines later on a missing field. - Auth errors are plain text. Calling
response.json()orjson.load()on a 400 or 401 raises a confusing parse error instead of showingInvalid API key. Read the body as text on non-2xx responses. - A 404 can be about your plan.
Endpoint not allowedmeans the route exists but your key's plan cannot use it. Do not retry it; check the endpoint list for your plan.
Here are the scripts from earlier handling the failure cases:
python3 first_call.py zzzznotacompany # an unknown company
INDIANAPI_KEY=wrong python3 first_call.py # a bad key
env -u INDIANAPI_KEY node first_call.mjs # no key at all
API error: Stock not found
HTTP 401: Invalid API key
HTTP 400: Missing API key
Each one exits with a non-zero status, so it also fails correctly inside a shell script or CI job.
9. Make it reusable
Once you call more than one endpoint, put the key header, timeout and both error checks in one place. This is client.py:
import json
import os
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
BASE_URL = "https://stock.indianapi.in" # change for your plan
class IndianAPIError(Exception):
pass
def get(path, **params):
"""GET a JSON endpoint; raise IndianAPIError for HTTP errors and {"error": ...} bodies."""
query = f"?{urlencode(params)}" if params else ""
request = Request(
f"{BASE_URL}{path}{query}",
headers={"X-Api-Key": os.environ["INDIANAPI_KEY"], "Accept": "application/json"},
)
try:
with urlopen(request, timeout=20) as response:
data = json.load(response)
except HTTPError as err:
raise IndianAPIError(f"HTTP {err.code}: {err.read().decode().strip()}") from None
if isinstance(data, dict) and "error" in data:
raise IndianAPIError(data["error"])
return data
And the Node equivalent, client.mjs:
const BASE_URL = "https://stock.indianapi.in"; // change for your plan
export async function get(path, params = {}) {
const url = new URL(path, BASE_URL);
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
const response = await fetch(url, {
headers: { "X-Api-Key": process.env.INDIANAPI_KEY ?? "", Accept: "application/json" },
signal: AbortSignal.timeout(20_000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${(await response.text()).trim()}`);
const data = await response.json();
if (data?.error) throw new Error(data.error);
return data;
}
Using it takes one line per call, and failures become ordinary exceptions you can catch:
from client import get, IndianAPIError
for stock in get("/trending")["trending_stocks"]["top_gainers"][:3]:
print(f"{stock['company_name']:<28} {stock['price']:>8} +{stock['percent_change']}%")
try:
get("/stock", name="zzzznotacompany")
except IndianAPIError as err:
print("caught:", err)
Hitachi Energy India 31610 +10.72%
Amber Enterprises India 6760 +8.77%
ITI 266.55 +6.17%
caught: Stock not found
The Node version produces identical output with import { get } from "./client.mjs".
Troubleshooting checklist
Work down this list when a call fails:
Missing API key(400): the header is not reaching the server. Checkecho "${INDIANAPI_KEY:+set}"printsset, and that the header name is exactlyX-Api-Key.Invalid API key(401): the key is wrong, expired or rotated. Copy it again from your dashboard, and check for a stray space or newline.Endpoint not allowed(404): the path may be misspelled, or your plan may not include it. Compare against the endpoints for your plan.Stock not found(200): try the exchange symbol (symbol=TCS) instead of a long company name, or check the spelling.- A timeout or connection error: confirm the host matches your plan and that you have network access. Retry once or twice with a short delay, not in a tight loop.
- A quota or rate-limit response: review your usage in the dashboard before retrying. Retrying without a limit only burns more requests.
Good habits from day one
- Call from a server, never from browser code. Anything in client-side JavaScript is visible to visitors, including your key. Put a small server or API route in front of the API and keep the key in server-side configuration.
- Cache repeated reads. Quota is a monthly allowance, not a target. A dashboard that refreshes every few seconds can spend it quickly, so cache responses for a sensible interval.
- Request only what you use. The
/stockpayload is large. Extract the fields you need on the server instead of passing everything onward. - Set a timeout on every request and surface errors instead of swallowing them.
- Never log request headers or commit the key. If it leaks, rotate it.
Next steps
Pick the endpoints your project needs, estimate your call volume against your plan's monthly quota, and wrap your calls in the helper from step 9. Browse the Indian API Hub for the available APIs and their reference documentation, and compare plans at indianapi.in once you know how much traffic you will send.
Output in this guide was captured from the live API on 14 November 2026. Market data shown is for illustration, is informational, and is not investment advice.