What Is an API?
An API — Application Programming Interface — is a contract between two pieces of software. "Send me this data in this format, and I will send you back a response in this format." That is it at its core.
In finance, APIs are everywhere. Market data providers expose APIs so you can fetch prices. Brokers expose APIs so you can submit orders. Risk systems expose APIs so dashboards can display positions. Your own internal services expose APIs to each other.
Understanding how to build and consume APIs is one of the most practically useful skills in modern software development.
REST: The Dominant Pattern
REST (Representational State Transfer) is not a protocol — it is a set of conventions for designing web APIs. The vast majority of APIs you will encounter follow REST principles.
The Core Ideas
- Resources — everything is a resource identified by a URL:
/trades,/positions/AAPL,/accounts/42 - HTTP methods define actions: GET (read), POST (create), PUT (update), DELETE (remove)
- Stateless — each request contains all the information needed to process it
- JSON is the standard data format for request and response bodies
A Financial API Example
GET /api/v1/trades → List all trades
GET /api/v1/trades/12345 → Get specific trade
POST /api/v1/trades → Create a new trade
PUT /api/v1/trades/12345 → Update a trade
DELETE /api/v1/trades/12345 → Cancel a trade
GET /api/v1/positions → Current positions
GET /api/v1/positions?symbol=AAPL → Filtered positions
GET /api/v1/portfolio/risk → Portfolio risk metrics
HTTP Status Codes
The response status code tells the client what happened:
| Code | Meaning | Example |
|---|---|---|
| 200 | Success | Trade retrieved |
| 201 | Created | New trade submitted |
| 400 | Bad Request | Invalid trade data |
| 401 | Unauthorised | Missing or invalid API key |
| 404 | Not Found | Trade ID does not exist |
| 429 | Rate Limited | Too many requests |
| 500 | Server Error | Something broke internally |
Consuming APIs with Python
The requests library is the standard for making HTTP calls:
import requests # GET: fetch market data response = requests.get( "https://api.example.com/v1/prices", params={"symbols": "AAPL,GOOGL,MSFT"}, headers={"Authorization": "Bearer YOUR_API_KEY"}, timeout=10, ) if response.status_code == 200: data = response.json() for quote in data["quotes"]: print(f"{quote['symbol']}: {quote['price']}") elif response.status_code == 429: print("Rate limited — wait and retry") else: print(f"Error: {response.status_code} - {response.text}") # POST: submit a trade trade_data = { "symbol": "AAPL", "quantity": 100, "price": 150.25, "side": "BUY", "order_type": "LIMIT", } response = requests.post( "https://api.example.com/v1/orders", json=trade_data, headers={"Authorization": "Bearer YOUR_API_KEY"}, timeout=10, ) if response.status_code == 201: order = response.json() print(f"Order created: {order['order_id']}")
Error Handling and Retries
Production API clients need to handle failures gracefully:
import time def fetch_with_retry(url, headers, max_retries=3): for attempt in range(max_retries): try: response = requests.get(url, headers=headers, timeout=10) if response.status_code == 200: return response.json() elif response.status_code == 429: wait = int(response.headers.get("Retry-After", 5)) time.sleep(wait) continue else: response.raise_for_status() except requests.exceptions.Timeout: if attempt < max_retries - 1: time.sleep(2 ** attempt) continue raise raise Exception(f"Failed after {max_retries} retries")
Building APIs with FastAPI
FastAPI is the modern Python framework for building APIs. It is fast, has automatic documentation, and integrates type hints beautifully:
from fastapi import FastAPI, HTTPException from pydantic import BaseModel app = FastAPI(title="Trading API") class TradeRequest(BaseModel): symbol: str quantity: int price: float side: str # "BUY" or "SELL" class TradeResponse(BaseModel): trade_id: str symbol: str quantity: int price: float side: str status: str @app.get("/api/v1/positions") def get_positions(symbol: str = None): positions = load_positions() if symbol: positions = [p for p in positions if p.symbol == symbol] return {"positions": positions} @app.post("/api/v1/trades", response_model=TradeResponse, status_code=201) def create_trade(trade: TradeRequest): # Validate the trade if trade.quantity <= 0: raise HTTPException(400, "Quantity must be positive") if trade.side not in ("BUY", "SELL"): raise HTTPException(400, "Side must be BUY or SELL") # Process the trade result = execute_trade(trade) return result
FastAPI automatically generates interactive documentation (Swagger UI) at /docs, validates request bodies against the Pydantic models, and returns appropriate error responses.
API Design Best Practices
Version your API — put /v1/ in the URL. When you need breaking changes, release /v2/ while keeping /v1/ running.
Use consistent naming — plural nouns for collections (/trades, not /trade), kebab-case for multi-word resources (/market-data).
Pagination — never return unbounded lists. Use ?limit=100&offset=0 or cursor-based pagination.
Rate limiting — protect your API from abuse. Return 429 with a Retry-After header.
Authentication — API keys for simple cases, OAuth for complex ones. See our guide on security and authentication.
Beyond REST
REST is dominant but not the only option:
- WebSockets — for real-time data like live market prices. The server pushes updates instead of the client polling.
- GraphQL — clients specify exactly what data they want. Good for complex queries, common in modern frontend applications.
- gRPC — binary protocol, much faster than REST. Used in performance-sensitive internal services.
For understanding how these protocols work under the hood, see our networking fundamentals guide. And for the security considerations that every financial API must address, see security and authentication.
Want to go deeper on APIs and REST for Financial Data?
This article covers the essentials, but there's a lot more to learn. Inside Quantt, you'll find hands-on coding exercises, interactive quizzes, and structured lessons that take you from fundamentals to production-ready skills — across 50+ courses in technology, finance, and mathematics.
Free to get started · No credit card required