Authentication overview
Finnhub secures access to its financial data APIs through an API key authentication mechanism. This method grants client applications permission to retrieve various data types, including real-time stock quotes, historical data, forex rates, cryptocurrency prices, economic calendars, and financial news. Each API key is unique to a user account and is essential for making authenticated requests to Finnhub's API endpoints. Without a valid API key, requests will be rejected, ensuring that only authorized users can consume Finnhub's data services.
The API key functions as a bearer token, meaning it is passed with each request, typically within the Authorization header. This approach allows Finnhub's servers to identify the requesting application and verify its subscription level and access permissions before serving data. The use of API keys is a common practice for authenticating access to web services, offering a balance of security and ease of implementation for developers.
Supported authentication methods
Finnhub primarily supports API key authentication for all its REST and WebSocket APIs. This method is straightforward to implement and manage, making it suitable for a wide range of applications from simple scripts to complex financial platforms. The API key acts as the sole credential required for accessing data, simplifying the authentication flow.
| Method | When to Use | Security Level |
|---|---|---|
| API Key | All Finnhub API interactions (REST and WebSocket) | Moderate (when combined with HTTPS and proper key management) |
While API keys are effective for access control, their security relies heavily on how they are managed and transmitted. Finnhub mandates the use of HTTPS/TLS encryption for all API communication to protect the API key and data in transit. This ensures that the key cannot be intercepted and used by unauthorized parties during network transmission. For more detailed information on secure communication, refer to a Mozilla Developer Network explanation of TLS.
Getting your credentials
To obtain your Finnhub API key, you must first register for an account on the Finnhub website. The process involves signing up and then navigating to your user dashboard where the API key is generated and managed.
- Sign Up/Log In: Go to the Finnhub homepage and either create a new account or log in to an existing one.
- Access Dashboard: Once logged in, you will typically be redirected to your personal dashboard or a similar account management page.
- Generate API Key: Within the dashboard, look for a section related to 'API Key' or 'Developer Settings'. Finnhub provides a clear interface to generate your unique API key.
- Copy Your Key: After generation, the API key will be displayed. Copy this key immediately and store it in a secure location. It is crucial to treat this key as sensitive information, similar to a password.
- Key Management: Your dashboard also allows you to revoke existing API keys and generate new ones if needed. This functionality is important for security best practices, such as rotating keys periodically or revoking compromised keys.
Finnhub's official documentation portal provides up-to-date instructions for managing API keys, including steps for generation, viewing, and revocation. Remember that the free tier offers 500 API calls per month, which may have limited data access, and an API key is required even for free tier usage.
Authenticated request example
Once you have obtained your API key, you can include it in your API requests. For Finnhub's REST API, the API key is typically passed as a query parameter or within the Authorization header as a bearer token. While both methods are supported, using the Authorization: Bearer header is generally preferred for security and adherence to modern API design principles.
Using the Authorization header (recommended)
This method involves setting the Authorization header with the value Bearer YOUR_API_KEY.
import requests
API_KEY = "YOUR_FINNHUB_API_KEY"
SYMBOL = "AAPL"
headers = {
"Authorization": f"Bearer {API_KEY}"
}
response = requests.get(f"https://finnhub.io/api/v1/quote?symbol={SYMBOL}", headers=headers)
if response.status_code == 200:
data = response.json()
print(data)
else:
print(f"Error: {response.status_code} - {response.text}")
Using a query parameter
Alternatively, you can pass the API key directly as a query parameter named token in the URL. While simpler for quick tests, this method is less secure as the API key might be logged in server logs or browser history.
const API_KEY = "YOUR_FINNHUB_API_KEY";
const SYMBOL = "MSFT";
fetch(`https://finnhub.io/api/v1/quote?symbol=${SYMBOL}&token=${API_KEY}`)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Finnhub also provides SDKs in various languages, including Python and JavaScript, which abstract away the details of constructing authenticated requests, making integration easier. These SDKs typically have a method to initialize the client with your API key.
Security best practices
Protecting your Finnhub API key is paramount to maintaining the security and integrity of your applications and data. Adhering to these best practices can mitigate common security risks:
- Do Not Embed Keys Directly in Code: Avoid hardcoding API keys directly into your application's source code, especially for client-side applications or publicly accessible repositories. This practice can lead to key exposure.
- Use Environment Variables: Store API keys in environment variables (e.g.,
FINNHUB_API_KEY) on your server or development machine. This keeps them out of your codebase and configuration files. For cloud environments, consider using secret management services like AWS Secrets Manager or Google Cloud Secret Manager. - Server-Side Access: Whenever possible, make API calls from your server-side application rather than directly from client-side code (e.g., JavaScript in a web browser). This prevents the API key from being exposed to end-users.
- Restrict IP Addresses (if available): If Finnhub offers IP address whitelisting, configure it to allow API calls only from your application's known server IP addresses. This adds an extra layer of security, preventing unauthorized use even if your key is compromised.
- Regular Key Rotation: Periodically generate new API keys and revoke old ones. This practice limits the window of opportunity for a compromised key to be exploited.
- Monitor Usage: Regularly check your API usage statistics in the Finnhub dashboard for any unusual activity that might indicate unauthorized key usage.
- Secure Development Practices: Implement secure coding practices throughout your application development lifecycle. This includes input validation, error handling, and protecting sensitive data within your application.
- HTTPS Everywhere: Always ensure that all communications with the Finnhub API use HTTPS. Finnhub enforces this, but it's a critical reminder for any API interaction to protect data in transit.
- Avoid Public Repositories: Never commit API keys or configuration files containing keys to public version control systems like GitHub. Use
.gitignorerules to exclude such files. - Least Privilege: If Finnhub offers different key types or scopes, use the key with the minimum necessary permissions required for your application's functionality.