StockAP.

STOCKAP DEVELOPER GUIDES

How to use a stock API in Python

By StockAP · Updated November 24, 2026

Fetch an AAPL quote with Python, keep your API key private and handle stale data and request errors.

A useful stock integration needs more than a price. It needs an instrument, a source timestamp and a clear response when the data is unavailable. This walkthrough uses StockAP’s authenticated REST endpoint for one AAPL quote. It runs on your backend, not in public frontend JavaScript.

1. Create a key and keep it on your server

Sign in to StockAP, create an API key in your dashboard and store it as STOCKAP_API_KEY in your server environment. Do not commit the value, paste it into a URL or include it in a screenshot. Check your account’s request limits before choosing a polling interval.

2. Request an AAPL quote

This example uses only Python’s standard library. It prints the returned data rather than assuming every provider supplies the same optional fields.

import json, os
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError

request = Request(
    "https://stockap.com/v1/quotes?market=stock&symbol=AAPL",
    headers={"Authorization": "Bearer " + os.environ["STOCKAP_API_KEY"]},
)
try:
    with urlopen(request, timeout=30) as response:
        payload = json.load(response)
    quote = payload["data"]
    print("Market:", payload["market"])
    print("Stale:", quote.get("stale"))
    print(quote)
except HTTPError as error:
    print("HTTP status:", error.code)
except URLError:
    print("Request unavailable; keep the previous quote marked stale.")

3. Show the timestamp with the price

The response envelope contains data, market and received_at. The receipt time tells you when StockAP served the response; it is not the trade time. Quote freshness uses data.time, in milliseconds, and the stale field. The current authenticated endpoint marks a quote stale when its time is missing or more than 60 seconds old. A closed market can therefore produce a stale quote without implying an outage.

4. Handle failures without creating a request storm

A 429 response means you should back off rather than immediately retry. An authentication error needs a valid key and account access. A 404 may indicate an unavailable instrument; a temporary upstream failure can produce 502. Use bounded retries with increasing delays for transient failures. Keep the last successful result visibly dated instead of replacing missing values with zero.

5. Add history when you need a chart

Use the candles endpoint with interval=1d, 1wk or 1mo. Start by checking the stored dates for AAPL; do not assume every symbol has an identical start date or uninterrupted sessions. Fetch a shared server-side snapshot for your users instead of making one upstream request per browser. See the Stock API product page for the supported request pattern and account setup.