import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/stockprice',
params={'ticker': 'AAPL'},
headers={'X-Api-Key': API_KEY},
)
print(response.json())Prerequisites
- Python 3.7+ installed
- The
requestslibrary (pip install requests) - A free API Ninjas API key
Step 1: Get your API key
Create a free account at api-ninjas.com/register. After signing in, copy your API key from your profile page. No credit card required.
Step 2: Install requests
pip install requestsStep 3: Make the API request
The Stock Price endpoint accepts a ticker query parameter and expects your API key in the X-Api-Key header:
import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/stockprice',
params={'ticker': 'AAPL'},
headers={'X-Api-Key': API_KEY},
)
print(response.json())Step 4: Use the response
The API returns a JSON object that looks like this:
{
"ticker": "AAPL",
"name": "Apple Inc.",
"price": 195.89,
"exchange": "NASDAQ",
"updated": 1717603200
}price is in the listing exchange's native currency (USD for US exchanges).updated is a Unix timestamp of the last quote update.
Complete example
A production-ready version that reads the API key from an environment variable and adds a request timeout:
import os
import requests
API_KEY = os.environ['API_NINJAS_KEY']
URL = 'https://api.api-ninjas.com/v1/stockprice'
def get_stock_price(ticker: str) -> dict:
response = requests.get(
URL,
params={'ticker': ticker},
headers={'X-Api-Key': API_KEY},
timeout=10,
)
response.raise_for_status()
return response.json()
if __name__ == '__main__':
quote = get_stock_price('AAPL')
print(f"{quote['name']} ({quote['ticker']})")
print(f"Price: ${quote['price']}")
print(f"Exchange: {quote['exchange']}")Run with: export API_NINJAS_KEY=your_key && python stock.py
Fetching prices for multiple tickers
Loop through a watchlist to print quotes for each ticker:
tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'NVDA']
for ticker in tickers:
quote = get_stock_price(ticker)
print(f"{ticker:6} ${quote['price']:>8.2f} {quote['exchange']}")Error handling
Handle invalid tickers, missing keys, and rate limits explicitly:
from requests.exceptions import HTTPError
try:
quote = get_stock_price('AAPL')
except HTTPError as e:
if e.response.status_code == 400:
print('Invalid ticker symbol')
elif e.response.status_code == 401:
print('Invalid or missing API key')
elif e.response.status_code == 429:
print('Rate limit exceeded — slow down requests')
else:
print(f'HTTP error: {e}')Saving prices to a DataFrame and CSV
For analysis or backtesting, dump quotes into a pandas DataFrame and save to CSV:
import pandas as pd
tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'NVDA']
rows = [get_stock_price(t) for t in tickers]
df = pd.DataFrame(rows)
df.to_csv('prices.csv', index=False)
print(df)Related APIs
Pair the Stock Price API with Earnings Calendar, Market Cap, and Stock News to build a complete equity-research workflow.