NewConnect Claude, Cursor, ChatGPT, and other AI agents to API Ninjas via our MCP server

How to Get Stock Price in Python

Stock Price APIUpdated May 23, 2026
To get a stock price in Python, send a GET request to the API Ninjas Stock Price endpoint with a ticker symbol and your API key. Here's a complete working example:
stock.py
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

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

Shell
pip install requests

Step 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:

stock.py
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:

JSON
{
  "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:

stock.py
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:

Python
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:

Python
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:

Python
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)

Pair the Stock Price API with Earnings Calendar, Market Cap, and Stock News to build a complete equity-research workflow.

Frequently asked questions

Is the stock price real-time or delayed?

The Stock Price API returns the most recent quote available. Quotes may be delayed by up to 15 minutes for some exchanges, which is standard for free-tier financial data.

Which exchanges and tickers are supported?

The API covers all major US exchanges (NYSE, NASDAQ) as well as many international exchanges. Use the standard ticker symbol — for non-US stocks, prefix with the exchange code (e.g., LSE:VOD).

How do I get historical stock prices?

The Stock Price endpoint returns current quotes only. For historical OHLC data, see the API Ninjas Earnings Calendar API for earnings-day prices, or use a dedicated historical-data provider.

Is there a free tier?

Yes. Every API Ninjas account includes a free tier — no credit card required.

What does the API return if the ticker is invalid?

A 400 status code with an error message. Wrap the request in a try/except block to handle invalid tickers gracefully.