Setting Up and Choosing an API
Before writing any code, you need two things: a data source and a proper project setup. For our stock price fetcher, we'll use a free API that provides real-time market data, and we'll structure our project so it's secure and maintainable from the start.
Choosing Your Stock API
Several free APIs provide stock price data. Here are three solid options for beginners:
Alpha Vantage offers a generous free tier with 25 requests per day. The documentation is clear, and the response format is straightforward. It's an excellent choice for learning.
Finnhub provides real-time data with 60 API calls per minute on the free plan. It has a modern REST API and good documentation.
Twelve Data offers 800 API calls per day for free, with a clean interface and multiple data formats.
For this project, Alpha Vantage works well because its responses are simple to parse and the rate limits are forgiving for development.
Sign up at your chosen provider's website. After registration, you'll receive an API key — a unique string that identifies your requests. Treat this key like a password.
Setting Up Your Project
Create a dedicated folder for your project and set up a Python virtual environment:
Create a requirements.txt file listing your dependencies:
requests
python-dotenv
Install them with pip install -r requirements.txt.
Protecting Your API Key
Never commit API keys to version control. Instead, use environment variables.
Create a .env file in your project root:
ALPHA_VANTAGE_API_KEY=your_key_here
Then add .env to your .gitignore:
.env
venv/
__pycache__/
The python-dotenv package loads these variables automatically, keeping your secrets out of your code and your Git repository.
Why This Structure Matters
This setup might seem like extra work for a small project, but it builds habits that matter. Professional projects always separate configuration from code. Starting with good practices means you won't accidentally expose credentials when you share your work.