Introduction to Twelve Data API in Node.js
- The Twelve Data API is a popular choice for fetching real-time and historical stock market data. It's easy to use and integrate with applications using Node.js. Below, we explore how to set up Node.js to work with Twelve Data for stock data retrieval, ensuring you can leverage its features efficiently.
Install Required Packages
- To interact with the Twelve Data API in Node.js, start by installing the necessary npm packages. You'll require
axios
for HTTP requests. If you haven't already, initialize a Node.js project with npm init
and install axios
using the following command:
npm install axios
Set Up Environment Variables
- Using environment variables to store your API key is a good practice. Create a
.env
file in the root of your project containing your Twelve Data API key as follows:
TWELVE_DATA_API_KEY=your_api_key_here
- Add the
dotenv
package to manage environment variables in your application:
npm install dotenv
Service to Fetch Stock Data
- Create a service file that encapsulates the logic for fetching stock data. Let's name this file
stockService.js
. The service will use the axios
library to make HTTP GET requests to the Twelve Data API.
require('dotenv').config();
const axios = require('axios');
const BASE_URL = 'https://api.twelvedata.com';
const API_KEY = process.env.TWELVE_DATA_API_KEY;
async function fetchStockData(symbol) {
try {
const response = await axios.get(`${BASE_URL}/quote`, {
params: {
symbol,
apikey: API_KEY
}
});
return response.data;
} catch (error) {
console.error('Error fetching stock data:', error);
throw error;
}
}
// Example usage
fetchStockData('AAPL')
.then(data => console.log(data))
.catch(error => console.error(error));
module.exports = { fetchStockData };
Include Error Handling
- Good error handling practices help ensure that your application remains robust and can gracefully handle failures such as network issues or invalid API responses. The error handling in the service above logs any issues and rethrows them for upstream handling.
Utilize the Stock Data in Your Application
- You can now import and use the
fetchStockData
function in your main application file or other modules. Here’s a simple example of how it might be used to get data for another stock:
const { fetchStockData } = require('./stockService');
fetchStockData('GOOGL')
.then(data => console.log('Google stock data:', data))
.catch(error => console.error('Failed to fetch Google stock data:', error));
Advanced Fetching: Using Multiple Endpoints
- The Twelve Data API offers many endpoints apart from just stock quotes, including time series, fundamental data, and more. You can extend your service by adding functions that fetch data from these endpoints. Modify your
stockService.js
to include calls to other API endpoints as needed.
async function fetchTimeSeries(symbol, interval) {
try {
const response = await axios.get(`${BASE_URL}/time_series`, {
params: {
symbol,
interval,
apikey: API_KEY
}
});
return response.data;
} catch (error) {
console.error('Error fetching time series data:', error);
throw error;
}
}
// Usage Example
fetchTimeSeries('AAPL', '1day')
.then(data => console.log('AAPL Time Series:', data))
.catch(error => console.error(error));
Conclusion
- Fetching stock market data using the Twelve Data API in Node.js is straightforward with the help of libraries like
axios
. By structuring your application effectively, keeping environment variables secret, and handling errors properly, you can create a robust system for stock data retrieval.
- Remember to refer to the official Twelve Data API documentation for more information on endpoints and customization options to further enhance your application's capabilities.