Getting started overview
Integrating with Finnhub's financial data API involves a series of steps designed to provide developers with access to market data, including real-time stock quotes, historical data, and economic indicators. The process begins with account creation and API key retrieval, followed by making an authenticated request to a Finnhub endpoint. Finnhub offers client SDKs in multiple programming languages, such as Python and JavaScript, to simplify integration.
This guide outlines the essential steps to get started with Finnhub, covering account registration, API key management, and executing your initial API call. It focuses on practical implementation to enable rapid development.
Here is a quick reference table for the Finnhub getting started process:
| Step | What to do | Where |
|---|---|---|
| 1. Sign Up | Create a Finnhub account to access the dashboard. | Finnhub Homepage |
| 2. Get API Key | Locate and copy your unique API key from the dashboard. | Finnhub Dashboard > API Key section |
| 3. Choose Language/SDK | Select a programming language (e.g., Python, JavaScript) or an SDK. | Finnhub API Documentation |
| 4. Install Dependencies | Install any necessary libraries or SDKs for your chosen language. | Package manager (pip for Python, npm for Node.js) |
| 5. Make Request | Write code to send an authenticated request to a Finnhub endpoint. | Your development environment |
| 6. Process Response | Handle the JSON data returned by the API. | Your application logic |
Create an account and get keys
Accessing the Finnhub API requires an account and an associated API key. This key authenticates your requests and links them to your subscription plan, which determines your access limits and data availability. Finnhub offers a free tier with 500 API calls per month, providing limited data access for initial testing and development.
Account Registration
- Navigate to the Finnhub website: Open your web browser and go to Finnhub's official homepage.
- Sign Up: Click on the 'Sign Up' or 'Get API Key' button, typically located in the top right corner or prominently displayed on the page.
- Provide Details: Enter your email address and create a password. You may also need to agree to the terms of service.
- Verify Email: Finnhub will send a verification email to the address you provided. Follow the instructions in the email to activate your account.
API Key Retrieval
Once your account is active and you've logged in, your API key will be available in your Finnhub dashboard:
- Log In: Access your Finnhub account dashboard using your registered credentials.
- Locate API Key: On the dashboard, there is typically a section labeled 'API Key' or 'Your API Key'. This section displays your unique string.
- Copy Key: Copy this API key. It is a sensitive credential and should be kept secure. You will use this key in every request to the Finnhub API.
For security best practices, avoid hardcoding your API key directly into your application code. Instead, use environment variables or a secure configuration management system. For information on managing API keys securely, refer to general guidelines on API key best practices from Google Cloud.
Your first request
After obtaining your API key, you can make your first request to the Finnhub API. This example demonstrates how to fetch real-time stock quotes using both Python and JavaScript. The Finnhub API uses REST principles and returns data in JSON format, which is a common data interchange format for web APIs, as described by json.org.
Endpoint Example: Stock Quote
We will use the following endpoint to get a real-time quote for a specific stock ticker:
GET https://finnhub.io/api/v1/quote?symbol=AAPL&token=YOUR_API_KEY
Replace YOUR_API_KEY with the key you retrieved from your Finnhub dashboard and AAPL with the stock symbol you wish to query.
Python Example
To use Python, you can install the official Finnhub Python client library:
pip install finnhub-python
Then, execute the following Python script:
import finnhub
import os
# Initialize Finnhub client with your API key
# It's recommended to store your API key in an environment variable
# Example: export FINNHUB_API_KEY="YOUR_API_KEY"
finnhub_client = finnhub.Client(api_key=os.environ.get("FINNHUB_API_KEY"))
# Get real-time quote for Apple (AAPL)
quote = finnhub_client.quote('AAPL')
print("Current Price (c):", quote['c'])
print("High Price (h):", quote['h'])
print("Low Price (l):", quote['l'])
print("Open Price (o):", quote['o'])
print("Previous Close (pc):", quote['pc'])
This script initializes the Finnhub client using an API key retrieved from an environment variable (a recommended security practice) and then prints various price metrics for Apple stock.
JavaScript Example (Node.js)
For JavaScript in a Node.js environment, you can use the node-finnhub library:
npm install node-finnhub
Then, create a JavaScript file (e.g., getQuote.js) and add the following code:
const finnhub = require('node-finnhub');
// It's recommended to store your API key in an environment variable
// Example: export FINNHUB_API_KEY="YOUR_API_KEY"
const apiKey = process.env.FINNHUB_API_KEY;
if (!apiKey) {
console.error('FINNHUB_API_KEY environment variable not set.');
process.exit(1);
}
const client = new finnhub.DefaultApi();
client.apiClient.authentications.api_key.apiKey = apiKey;
// Get real-time quote for Apple (AAPL)
client.quote("AAPL", (error, data, response) => {
if (error) {
console.error("Error fetching quote:", error);
} else {
console.log("Current Price (c):", data.c);
console.log("High Price (h):", data.h);
console.log("Low Price (l):", data.l);
console.log("Open Price (o):", data.o);
console.log("Previous Close (pc):", data.pc);
}
});
Run this script using node getQuote.js after setting the FINNHUB_API_KEY environment variable. This will execute the API call and log the stock quote data to your console.
Common next steps
After successfully making your first Finnhub API call, consider these next steps to further integrate financial data into your applications:
- Explore More Endpoints: Review the Finnhub API documentation to discover other available endpoints, such as historical candlestick data, company profiles, financial statements, and news.
- Implement WebSockets: For real-time data streaming, explore Finnhub's WebSocket API. This allows for continuous updates without polling, which can be more efficient for applications requiring immediate market data. The WebSocket API documentation is part of the main Finnhub API reference.
- Error Handling: Implement robust error handling in your application to gracefully manage API rate limits, invalid requests, or network issues. The API will return specific HTTP status codes and error messages that can be used for debugging.
- Optimize API Usage: Understand Finnhub's rate limits and optimize your API calls to stay within your plan's allowance. This might involve caching data, using WebSockets for real-time needs, and fetching data only when necessary.
- Upgrade Your Plan: If your application requires higher call volumes, more extensive data, or real-time streaming, consider upgrading from the free tier to a paid Finnhub plan.
- Explore SDKs: If you are using a language not covered in the examples, check the Finnhub documentation for other SDKs (Go, Ruby, C#, Java, PHP, R, Swift, Kotlin), which can abstract away much of the HTTP request and JSON parsing logic.
Troubleshooting the first call
Encountering issues during your initial API call is common. Here are some troubleshooting tips for Finnhub:
- Invalid API Key: Double-check that you have copied your API key correctly from the Finnhub dashboard. A common error is including extra spaces or characters. Ensure it's passed as the
tokenparameter in the URL or correctly configured in the SDK. - Rate Limit Exceeded: If you receive a
429 Too Many Requestserror, it means you have exceeded the call limit for your current plan (e.g., 500 calls/month for the free tier). Wait for the limit to reset or consider upgrading your plan. - Incorrect Endpoint or Parameters: Verify that the API endpoint URL and all query parameters (like
symbol) exactly match the Finnhub API documentation. Typos are a frequent cause of errors. - Network Issues: Ensure your development environment has an active internet connection and that no firewalls or proxies are blocking outgoing requests to
finnhub.io. - JSON Parsing Errors: If your code struggles to parse the response, confirm that the API returned valid JSON. Sometimes, an error message from the API itself might not be valid JSON, or your parsing logic might be incorrect.
- Environment Variable Issues: If you are using environment variables for your API key, ensure they are correctly set and accessible by your script. For example, in a terminal, running
echo $FINNHUB_API_KEYshould display your key after setting it. - SDK Specific Errors: If using an SDK, consult the specific SDK's documentation or GitHub repository for common issues. Ensure the SDK is installed correctly and updated to the latest version.
- Check Finnhub Status Page: Occasionally, API issues can stem from the provider. Check the Finnhub website or social media channels for any service announcements or outages.